jquery.form / validate插件仅允许在输入更改时提交

时间:2012-06-11 16:40:52

标签: javascript jquery jquery-validate jquery-forms-plugin

我想使用jQuery.Form / Validate插件,只有在实际更改任何输入时才允许提交我的表单。

使用beforeSubmit:http://jquery.malsup.com/form/#options-object有回调逻辑。但是,我似乎无法使其发挥作用。

这是我到目前为止所拥有的:

$(document.body).on('click', 'input[type="submit"]', function(){
 var $form =$('form');

$form.validate({
  submitHandler: function($form) {
   $($form).ajaxSubmit({
  beforeSubmit: function(arr, $form){           
      var value = '', storedValue='';
      $($form+':input').each(function (index, el) {
  value=$(el).val();
  storedValue=$(el).data("stored");            
      if(value!=storedValue){
      console.log("Changed");   return true;
  } 
      else {
      return false; console.log("NOT changed");
  }
});   

...success handling, etc..

beforeSubmit: function(arr, $form) { 
  var value = '', storedValue='';
  $($form+':input').each(function (index, this) {
    value=this.value;
    storedValue=$(this).data("stored");            
        if(value!=storedValue){
          console.log("Changed");return true;
        } 
        else {
         return false; console.log("NOT changed");
        }
  });                   
}

这是HTML:

<form id="myForm">
  <input data-stored="my title" value="my title"/>
  <textarea data-stored="my description">my description</textarea>
  <input type="submit" value="submit/>
</form>

目前,console.log显示"Changed",无论storedValue是否与输入相等。

1 个答案:

答案 0 :(得分:1)

首先,它永远不会显示“未更改”,因为它returns false才会触及该部分。你也应该过滤掉提交按钮,因为你可能没有检查它的值。

$($form+':input').not(':submit').each(function(index, this) {
    value = this.value;
    storedValue = $(this).data("stored");
    if (value != storedValue) {
        console.log("Changed");
        return true;      
    }
    else {       
        console.log("NOT changed");
        return false;
    }
});

<强>更新 在@wirey的大力帮助下,我们(@timrpeterson和@wirey)共同制定了一个解决方案。我没有在each()循环中返回true / false,而是增加了一个值totalChanged,并在each()循环后评估它是否大于0。

这是代码:

beforeSubmit: function(arr, $form){   
var value = '', storedValue='', totalChanged=0;
$('#myForm :input').not(':submit,:hidden').each(function (i, el) {
  //console.log($(this));
    console.log($($form));
    value=$(el).val(); 
    storedValue=$(el).data("stored");          
    if (value != storedValue) {  
      totalChanged++;    
    }
    else {     
    }
}); //each

  if(totalChanged>0){
     console.log("at least one changed");
     return true;
  }
  else{
     console.log("All NOT changed");
     return false;
  }
} //beforeSubmit
相关问题