80

How can I use onChange or a similar event for all form elements? I don't want to use onChange for each field separately.

Mori
  • 8,137
  • 19
  • 63
  • 91
  • why not? In the HTML event you could call the same function everytime, so it's a matter of copy-pasting probably no more then 20 characters and writing 1 function. – 11684 May 25 '12 at 20:18
  • 1
    does [this](http://stackoverflow.com/questions/10546076/common-event-for-all-elements-on-form) help? – Nadir Sampaoli May 25 '12 at 20:20

2 Answers2

138

You can use the change event on the form element:

const form = document.querySelector('form');
form.addEventListener('change', function() {
    alert('Hi!');
});
Mori
  • 8,137
  • 19
  • 63
  • 91
  • 3
    Thanks. After doing some tests - I'll just add that the 'change' event here is just perfect for this, because for text inputs it doesn't fire for every keydown, but, just like we would expect - on blur if there was a change. Like here: http://jsfiddle.net/54dftpL6/ - so it seems to be **the** solution for "save form automatically on any change" task, which I've just completed in time much shorter than I expected :) – konrados Aug 26 '18 at 15:51
  • 127
    Thumbs up for answering your own question 6 years later. – Qwerty Mar 06 '19 at 19:57
  • 2
    A form control that is not a descendant of its form element (possible with the `form` attribute) will not bubble the event up to the form element. To accomodate such cases we could instead add the event listener to `document.body` and check `event.target.form` matches the intended form. – Jemi Salo Sep 17 '20 at 19:56
  • As of 2022-06 a `textarea` inside your form will not trigger the form's change event :( – rodrigo-silveira Jun 09 '22 at 00:55
  • If you have a reset button in the form you need to subscriber to "reset" event as well. – ya.teck Jul 04 '23 at 07:16
43

If you are using jQuery, you can use the change event on the form element, because in jQuery the event bubbles up.

$('#formId').change(function(){...});

If you are using plain javascript, the change event does not bubble (at least not cross browser). So you would have to attach the event handler to each input element separately:

var inputs = document.getElementsByTagName("input"); 
for (i=0; i<inputs.length; i++){
   inputs[i].onchange = changeHandler;
}

(of course, you would have to do a similar thing to all selects and textareas)

Steve
  • 8,609
  • 6
  • 40
  • 54