Languages
[Edit]
EN

JavaScript - fire onchange event manually

5 points
Created by:
Dexter
300

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');
    event.initEvent('change', false, true); // onchange event
    element.dispatchEvent(event);
} else {
    element.fireEvent('change'); // only for backward compatibility (older browsers)
}

 

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>
<html>
<head>
  <script>
    
    var dispatchEvent = function(element, eventName) {
        if ('createEvent' in document) {
            var event = document.createEvent('HTMLEvents');
        	event.initEvent(eventName, false, true);
            element.dispatchEvent(event);
        } else {
            element.fireEvent(eventName); // only for backward compatibility (older browsers)
        }
    };
    
  </script>
</head>
<body>
  <input id="element" value="Old value ..." onchange="console.log('onchange fired!')" />
  <script>

    var element = document.querySelector('#element');
    
    element.addEventListener('change', function() {
    	console.log('addEventListener(\'onchange\', ...) fired!');
    });
    
    
    // Usage example:
    
    setTimeout(function() {
        element.value = 'NEW!!! value ...';
    	dispatchEvent(element, 'change'); // <------ fires an event simulating a change in values
    }, 1000);
    
  </script>
</body>
</html>
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.

❤️💻 🙂

Join