Categories
JavaScript Answers

How to Watch for Form Data Changes in jQuery?

Spread the love

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.

For instance, if we have the following form:

<form>
  <input>
  <button type='submit' id='mybutton'>
    submit
  </button>
</form>

Then we can listen for changes of the input by writing:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});

$('#mybutton').click(function() {
  if ($(this).closest('form').data('changed')) {
    console.log('form changed')
  }
});

We select the input elements in the form with $(“form :input”) .

Then we call change on it with a callback that gets the closest form element of the input.

And we call data with the 'changed' key and true as the value of the key.

Next, we get the button with ID mybutton with $(‘#mybutton’) .

We call click on it to listen to click events on it.

We call it with a callback that gets the form with $(this).closest(‘form’) .

And we get the 'changed' data value from the form element object with the data method.

If the input value changed and we click the button, we should see 'form changed' logged.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.