Find out if anything has changed in the form using jQuery

Asked

Viewed 584 times

1

Hello, I would like to know if there is any method in jQuery that returns if there have been changes in the initial form or not. For example, I have 3 empty fields, and as soon as I modify some of them. jQuery return me something...

Thank you.

2 answers

3


You don’t need jQuery.

document.getElementById('campo').addEventListener('input', function () {
    /* faz alguma coisa */
});

You can use change in place of input if you want your code to run only when the user leaves the field.

If you want to do it for everybody, you can do it

var toArray = Array.prototype.slice.call;
function doSomething() {
    /* faz alguma coisa */
}
toArray(document.querySelectorAll('input[type="text"]')).forEach(function (input) {
    input.addEventListener('input', doSomething);
});

There in the querySelectorAll you can restrict only to some inputs, if you want checkboxes, if you want only the inputs of a certain form...

  • I will test, but I don’t know if this is exactly what I want, because instead of 'field' I should specify the id of one of the fields not? I wanted a global way, anywhere the user modified in my document I discovered (I don’t know if I was clear).

  • I edited the answer.

1

You can also use jQuery’s change function, it would look like this:

$(':input').change(function(){  
  //Ação desejada.
}); 

In this small example I marked to select all INPUT fields, but you can through the jQuery selector select the desired fields.

In Desired Action, you put the code to be executed when a user modifies the selected field, such as giving feedback that the field has been populated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.