I'd like to use the jQuery.Form/Validate plugins to only allow my form to be submitted if any of inputs were actually changed.
There is callback logic for this using beforeSubmit:
: http://jquery.malsup.com/form/#options-object. However, I can't seem to make it work.
Here's what I have so far:
$(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");
}
});
}
Here's the 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>
Currently the console.log shows, "Changed"
regardless of whether the storedValue
is equal or not to the input.
First of all it will never show "Not Changed" since it
returns false
before it hits that part. You should filter out the submit button too since you probably aren't checking its value.UPDATE With great assistance from @wirey, together we've (@timrpeterson and @wirey) put together a solution. Instead of returning true/false within the
each()
loop, I incremented a value ,totalChanged
, and assessed after theeach()
loop whether or not it was greater than 0.here's the code: