mike mike - 5 months ago 22
jQuery Question

jquery form change

In jQuery, is there a simple way to test if ANY of a forms 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.