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');
    event.initEvent('change', false, true); // onchange event
} 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 event = document.createEvent('HTMLEvents');
        	event.initEvent(eventName, false, true);
        } else {
            element.fireEvent(eventName); // only for backward compatibility
  <input id="element" value="Old value ..." onchange="console.log('onchange fired!')" />

    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 event simulating change value
    }, 1000);
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.

❤️💻 🙂