How can I trigger an onchange event manually in javascript?

JavascriptFront End TechnologyObject Oriented Programming

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!
raja
Published on 27-Nov-2019 10:45:41
Advertisements