Reputation: 34271
I have a HTML form that contains text fields, checkboxes, radiobuttons and a submit button.
I'd like that submit button is enabled only if contents of fields are modified. Now here is the catch: if the user modifies field contents back to original values, the form button should be disabled again.
How to achieve this with jQuery? Are there any kind of general solution or script that I could use with any form?
Edit: What I am asking can't be done with simple dirty state tracking.
Upvotes: 2
Views: 9860
Reputation: 159
What you could do is setup a jquery script to scan the page on page load and check for a form, inventory the fields and their values, and then check against that input reference array whenever an input is updated.
Upvotes: 0
Reputation: 1583
You can use dirtyField plugin instead and set denoteDirtyForm: true. Now if your form has "dirtyForm" class means you have unsaved changes.
Upvotes: 0
Reputation: 14551
It should be possible to save the whole form object (either as it is, or by iterating with .each() and storing the data in a map), and then do the same onSubmit and compare both values.
Upvotes: 0
Reputation: 11185
I havent tested whats below :-) But is that what you mean ?
$(document).ready(function() {
$("#myform :input").attr("init",$(this).val()).bind("change.dirty", function(evt) {
if ($(this).val()!=$(this).attr("init")) $(this).addClass("dirty");
else $(this).removeClass("dirty");
$('#thebutton').attr("disabled",!$("#myform .dirty").size());
});
});
*-pike
Upvotes: 0
Reputation:
This seems like a better answer.
1401-Using-jQuery-To-Leverage-The-OnChange-Method-Of-Inputs.htm
Upvotes: 1
Reputation: 41837
Just two steps:
Upvotes: 2
Reputation: 17288
Use dirty state tracking. Attach a boolean value (e.g. IsDirty) to every input control and toggle it whenever the value changes. While submitting the form check if atleast one or more values have changed and then submit the form. Otherwise display an alert to the user.
Another solution is to call a common function whenever a controls value changes. In this function you can set a global variable (IsDirty) to true if something changed and also enable/disable the submit button.
var isDirty = false;
function SomethingChanged(){
if( !isDirty ) isDirty = true;
btnSubmit.disabled = !isDirty;
}
Generic Function for any control
Assumptions: Add the initial value of each control to an attribute "InitVal"
function SomethingChanged(control){
if( control.value != control.InitVal )
control.IsDirty = true;
else
control.IsDirty = false;
}
In the above function to make it generic you can have separate functions for each type of control like TextBoxChanged and DropDownChanged etc. But have the following two attributes on each control
Upvotes: 4