mike mike - 1 month ago 11
Javascript Question

How do you handle a form change in jQuery?

In jQuery, is there a simple way to test if ANY of a form's elements have changed?

EDIT: I should have added that I only need to check on a

click()
event.

EDIT: Sorry I really should have been more specific! Say I have a form and I have a button with the following:

$('#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?

Answer

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.