How can I trigger an 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: 27-Nov-2019

24K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements