Sometimes, we want to programmatically force an onchange event on an input with JavaScript.
In this article, we’ll look at how to programmatically force an onchange event on an input with JavaScript.
How to programmatically force an onchange event on an input with JavaScript?
To programmatically force an onchange event on an input with JavaScript, we use the Event
constructor.
For instance, we write
const element = document.getElementById("input");
const event = new Event("change");
element.dispatchEvent(event);
to call getElementById
to select the input element.
Then we create a new Event
object that triggers the change event.
And then we call element.dispatchEvent
with event
to trigger the change event.
Conclusion
To programmatically force an onchange event on an input with JavaScript, we use the Event
constructor.