Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to detect if at least one field has been changed on an HTML form?

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?

like image 744
Marcus Avatar asked Mar 01 '09 00:03

Marcus


People also ask

How do you check that an HTML form has been changed?

$("#myform"). trackChanges(); and check if a form has changed: if ($("#myform").

What is dirty in HTML?

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).


1 Answers

Approach

  1. serialize the form (and all its values) before showing it (jQuery way, Prototype way)
  2. 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.';     } }; 
like image 96
Crescent Fresh Avatar answered Sep 22 '22 12:09

Crescent Fresh