Sahan H.
Sahan H.

Reputation: 472

javascript, looping fields and validating

I'm using below code to check some form fields and render datatable table on a button click. My intention is to stop the table from being rendered if any of the fields are empty. Apparently return false inside the loop is not working.

Is this the correct way to accomplish? any better ways?

$('#advance_search').click(function(){
  var ds = $('.advance_search .filter_field');

  $.each(ds, function(index, value){ //this loop checks for series of fields
    if ($(this).val().length === 0) {
      alert('Please fill in '+$(this).data('label'));
      return false;
    }
  });

  dt.fnDraw(); //shouldn't be called if either one of the field is empty

});

Upvotes: 1

Views: 94

Answers (2)

Esailija
Esailija

Reputation: 140228

If you look carefully, your return false is inside the $.each callback function, so it returns false for the caller of that function, not the "main function" you are in.

Try this:

$('#advance_search').click(function(){
    var ds = $('.advance_search .filter_field'), valid = true;

    $.each(ds, function(index, value){ //this loop checks for series of fields
        if($(this).val().length === 0) {
            alert('Please fill in '+$(this).data('label'));
            return (valid = false); //return false and also assign false to valid
        }
    });

    if( !valid ) return false;

    dt.fnDraw(); //shouldn't be called if either one of the field is empty

});

Upvotes: 3

Zuul
Zuul

Reputation: 16269

You could add a control variable to prevent the dt.fnDraw() from being called:

$('#advance_search').click(function(e){

  e.preventDefault();

  var check = 0, // Control variable
      ds    = $('.advance_search .filter_field');

  $.each(ds, function(index, value){ //this loop checks for series of fields
    if($(this).val().length === 0) {
      check++; // error found, increment control variable
      alert('Please fill in '+$(this).data('label'));
    }
  });

  if (check==0) { // Enter only if the control variable is still 0
    dt.fnDraw(); //shouldn't be called if either one of the field is empty
  }

});

Upvotes: 0

Related Questions