Trigger OnChange Event Manually in JavaScript



You can dispatch events on individual elements using the dispatchEvent method. Let's say you have an element test with an onChange event −

<input id="test" type="text"/>

Event handler −

document.querySelector('#test').addEventListener('change', () =>
console.log("Changed!"))

Triggering the event manually −

const e = new Event("change");
const element = document.querySelector('#test')
element.dispatchEvent(e);

This will log the following −

Changed!
Updated on: 2019-11-27T10:46:10+05:30

27K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements