Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to track changes in a form via javascript?

I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to

  • enable "save" button only when something has changed
  • alert if the user wants to close the page and something is not saved

Ideas?

like image 209
Ricardo Acras Avatar asked Oct 11 '08 14:10

Ricardo Acras


People also ask

Can you use JavaScript for forms?

With JavaScript at your side, you can process simple forms without invoking the server. And when submitting the form to a CGI program is necessary, you can have JavaScript take care of all the preliminary requirements, such as validating input to ensure that the user has dotted every i.

What is form handling in JavaScript?

Handling forms is a multipart process. First a form is created, into which a user can enter the required details. This data is then sent to the web server, where it is interpreted, often with some error checking.

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

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


2 Answers

Loop through all the input elements, and put an onchange handler on each. When that fires, set a flag which lets you know the form has changed. A basic version of that would be very easy to set up, but wouldn't be smart enough to recognize if someone changed an input from "a" to "b" and then back to "a". If it were important to catch that case, then it'd still be possible, but would take a bit more work.

Here's a basic example in jQuery:

$("#myForm")     .on("input", function() {         // do whatever you need to do when something's changed.         // perhaps set up an onExit function on the window         $('#saveButton').show();     }) ; 
like image 160
nickf Avatar answered Oct 10 '22 02:10

nickf


Text form elements in JS expose a .value property and a .defaultValue property, so you can easily implement something like:

function formChanged(form) {   for (var i = 0; i < form.elements.length; i++) {       if(form.elements[i].value != form.elements[i].defaultValue) return(true);   }   return(false); } 

For checkboxes and radio buttons see whether element.checked != element.defaultChecked, and for HTML <select /> elements you'll need to loop over the select.options array and check for each option whether selected == defaultSelected.

You might want to look at using a framework like jQuery to attach handlers to the onchange event of each individual form element. These handlers can call your formChanged() code and modify the enabled property of your "save" button, and/or attach/detach an event handler for the document body's beforeunload event.

like image 27
Dylan Beattie Avatar answered Oct 10 '22 02:10

Dylan Beattie