Languages
[Edit]
EN

JavaScript - fire onchange event manually

5 points
Created by:
Dexter
660

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

Quick solution:

element.dispatchEvent(new Event('change'));

 

Practical example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script>

    var dispatchEvent = function(element, event) {
        element.dispatchEvent(new Event(event));
    };

  </script>
</head>
<body>
  <input id="element" value="Old value ..." onchange="console.log('onchange event fired!')" />
  <script>

    var element = document.querySelector('#element');
    
    element.addEventListener('change', function() {
    	console.log('onchange event fired!');
    });
    
    
    // Usage example:

    function changeValue() {
        element.value = 'New value ...';
    	dispatchEvent(element, 'change');  // <------ fires an event simulating a change in values
    }

    setTimeout(changeValue, 1000);
    
  </script>
</body>
</html>

 

Alternative titles

  1. JavaScript - dispatch onchange event manually
  2. JavaScript - trigger onchange event manually
  3. JavaScript - fire change event manually
  4. JavaScript - dispatch change event manually
  5. JavaScript - trigger change event manually
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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