JavaScript - fire onchange event manually

5 points
Created by:

In this short article, we would like to show you how to trigger onchange evet manually in JavaScript.

Quick solution:

if ('createEvent' in document) {
    var event = document.createEvent('HTMLEvents');
    eventArg.initEvent('change', false, true);
} else {
    element.fireEvent('change'); // only for backward compatibility

Practical example

The main advantage of the below solution is the custom dispatchEvent function calls onchange property and listener function for change event keeping backward compatibility.

// ONLINE-RUNNER:browser;

<!doctype html>
    var dispatchEvent = function(element, eventName) {
        if ('createEvent' in document) {
            var eventArg = document.createEvent('HTMLEvents');
        	eventArg.initEvent(eventName, false, true);
        } else {
            element.fireEvent(eventName); // only for backward compatibility
  <input id="element" type="text" onchange="console.log('onchange fired!')" />

    // Usage example:
    var element = document.querySelector('#element');
    element.addEventListener('change', function() {
    	console.log('addEventListener(\'onchange\', ...) fired!');
    element.value = 'Some new value ...';
    dispatchEvent(element, 'change');
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé