I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to
Ideas?
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.
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.
$("#myform"). trackChanges(); and check if a form has changed: if ($("#myform").
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(); }) ;
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.
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