In jQuery, is there a simple way to test if any of a form's elements have changed?
Say I have a form and I have a button with the following click()
event:
$('#mybutton').click(function() { // Here is where is need to test if(/* FORM has changed */) { // Do something } });
How would I test if the form has changed since it was loaded?
To watch for form data changes in jQuery, we can listen for input changes. And when an input value changes, we add the changed data into the form element object. Then we can listen for changes of the input by writing: $("form :input").
The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected. For text fields or text areas, the change event occurs when the field loses focus, after the content has been changed.
$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.
You can do this:
$("form :input").change(function() { $(this).closest('form').data('changed', true); }); $('#mybutton').click(function() { if($(this).closest('form').data('changed')) { //do something } });
This rigs a change
event handler to inputs in the form, if any of them change it uses .data()
to set a changed
value to true
, then we just check for that value on the click, this assumes that #mybutton
is inside the form (if not just replace $(this).closest('form')
with $('#myForm')
), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() { if($(this).closest('form').data('changed')) { //do something } });
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() { var form_original_data = $("#myform").serialize(); $("#mybutton").click(function() { if ($("#myform").serialize() != form_original_data) { // Something changed } }); });
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