[英]jquery.form/validate plugin only allow submit if input is changed
我想使用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>
当前,无论storedValue
是否等于输入,console.log都会显示"Changed"
。
首先,它永远不会显示“ Not Changed”,因为它在到达该部分之前会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,而是增加了一个value, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.