JavaScript,循环字段和验证



我使用以下代码来检查一些表单字段并在单击按钮时呈现数据表表。我的目的是在任何字段为空时停止呈现表。显然,循环内的return false不起作用。

这是正确的完成方式吗?还有更好的方法吗?

$('#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
});

如果你仔细观察,你的return false$.each回调函数内,所以它returns false该函数的调用者,而不是你所在的"main 函数"。

试试这个:

$('#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
});

您可以添加一个控制变量来防止调用dt.fnDraw()

$('#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
  }
});

最新更新