Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 669
mike Avatar asked Jun 11 '10 18:06

mike


People also ask

How do you check whether a form is changed or not in jQuery?

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").

How does jQuery change work?

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.

What is '$' in jQuery?

$ 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.


2 Answers

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.

like image 99
Nick Craver Avatar answered Sep 20 '22 02:09

Nick Craver


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         }     });  }); 
like image 32
Udi Avatar answered Sep 21 '22 02:09

Udi