Sometimes, we want to programmatically trigger a change event on an input element with JavaScript.
In this article, we’ll look at how to programmatically trigger a change event on an input element with JavaScript.
Use the dispatchEvent Method
We can use the dispatchEvent
method on an element to trigger an event programmatically.
For instance, if we have the following HTML:
<input>
We can write:
const element = document.querySelector('input');
element.addEventListener('change', () => console.log('change'))
const event = new Event('change');
element.dispatchEvent(event);
to trigger the change event on an input.
We get the input with document.querySelector
.
Then we add a change event listener with the addEventListener
method.
Then we create a new event with the Event
constructor.
'change'
sets it to create the change event.
And then we call element.dispatchEvent
to trigger the event we created.
Therefore, we should see 'change'
logged from the change event listener.
Conclusion
We can trigger the change event programmatically on an input element with the Event
constructor.
Then we can call the dispatchEvent
method to dispatch the event.