How can I use onChange or a similar event for all form elements? I don't want to use onChange for each field separately.
Asked
Active
Viewed 8.0k times
67
Mori
- 8,305
- 16
- 59
- 90
-
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
-
1does [this](http://stackoverflow.com/questions/10546076/common-event-for-all-elements-on-form) help? – Nadir Sampaoli May 25 '12 at 20:20
2 Answers
107
You can use the change event on the form element:
var form = document.querySelector('form');
form.addEventListener('change', function() {
alert('Hi!');
});
Mori
- 8,305
- 16
- 59
- 90
-
2Thanks. 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
-
86
-
1A 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
42
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,469
- 6
- 39
- 53
-
13
-
@Mori - can you elaborate on your comment please, what support is there for form onchange now? – Tony Merryfield Feb 05 '16 at 13:58
-
8@Tony Merryfield: Now `formElement.addEventListener('change', doSomething);` works in all major browsers. – Mori Feb 05 '16 at 14:26
-
Thanks for the reply - do you know what the minimum IE version is that supports it? I can't find any decent information for the searches I've done - probably too generic in my search terms... :) – Tony Merryfield Feb 05 '16 at 14:44
-
1
-
That's great - thanks. I never did manage to find any information about this but have been using it on a project and works fine for the browsers we support :) – Tony Merryfield Feb 11 '16 at 10:41
-
1