I want to make a generic form validation script where I would compare a form’s existing data with the data that is submitted. The validation would fail if the submitted data is NOT different from that which exists on page load.
The problem is if one has multiple forms and one wants to validate the existing data for just a single form. Here’s a JSFiddle that’s seems pretty close to working but still isn’t: http://jsfiddle.net/aMUNh/33/
I think the problem with this JSFiddle is the $.each(function) and setting up the existingData JSON object.
HTML:
<form id="form1">
<input name='form1name1' value='form1value1'>
<input name='form1name2' value='form1value2'>
<input id="1" type="submit" value='submit'>
</form>
<form id="form2">
<input name='form2name1' value='form2value1'>
<input name='form2name2' value='form2value2'>
<input id="2" type="submit" value='submit'>
</form>
JS:
var existingData={}; //declaring the object to be cached
$("form").each(function(index){
existingData.id+=this.id;
existingData.id.data+=$(this).serialize();
});
var id='form1';
document.write('existingData:'+existingData.id.data);
$('input [type=submit]').click(function(){
var id='form'+this.id;
var submittedData=$(this.form).serialize();
if(submittedData==existingData.id.data){
console.log('nothing changed');
}
else console.log('this form changed');
});
The problem is with the formatting of your data references; just use the form’s
id. You need something like this: