Sunday, October 03, 2010

How clean is your form?

A secondary use for $.serialize() is altering a form's behavior if the user has updated the form since the document was loaded.  When the document is ready, the initial state of the form can be captured in a single variable that is easily compared.
$(document).ready(function() {
    var clean = $("#myform").serialize();
});
Now whenever a change event is fired on an element within the form, you can re-serialize the form and compare it to the original "clean" value to figure out if the form has been changed and update behavior if necessary.
$("#myform").delegate("input select textarea", "change", function(){
    var dirty = clean !== $("#myform").serialize();
    if (dirty) {
        enableSave();
        warnOnUnload();
    }
});
Kinda neat and a little more robust than other solutions.

0 Comments:

Post a Comment

Previous Posts

Powered by Blogger