I have an HTML form with over 20 fields. I also have a couple of links on the page which will lead the user away from the form... potentially without having saved any changes.
I want to warn (JS confirm) the user onClick of these links if any of the form fields have changed, but I don't want to create a huge switch statement that I then need to maintain as I add new fields to the form. I know how to create a long list of 'if' statements in Javascript, naming each of the fields and checking each value, but I don't want to do that if I can get away with it.
What's the easiest way to check if the user has changed at least one of the field values?
$("#myform"). trackChanges(); and check if a form has changed: if ($("#myform").
If you have observed, generally in web pages, once user performs some edit action on any of the fields the form is considered as dirty(edited)(even if data remains unchanged after editing).
Approach
"onbeforeunload"
event handlerIf 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.'; } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With