Entire form onChange

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

You can use the change event on the form element:

var form = document.querySelector('form');
form.addEventListener('change', function() {
    alert('Hi!');
});

Solution 2 - Javascript

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMoriView Question on Stackoverflow
Solution 1 - JavascriptMoriView Answer on Stackoverflow
Solution 2 - JavascriptSteveView Answer on Stackoverflow