Approach
- serialize the form (and all its values) before showing it (jQuery way, Prototype way)
- serialize it again in a
"onbeforeunload"event handler
If the two don’t match, then they must’ve changed the form, so return a string (eg “You have unsaved data”) from your onbeforeunload handler.
This method allows the form fields to evolve while the “confirm if changed” logic remains the same.
Example (mixed javascript and jquery)
var form_clean;
// serialize clean form
$(function() {
form_clean = $("form").serialize();
});
// compare clean and dirty form before leaving
window.onbeforeunload = function (e) {
var form_dirty = $("form").serialize();
if(form_clean != form_dirty) {
return 'There is unsaved form data.';
}
};