How do I programmatically force an onchange event on an input?

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly


In jQuery I mostly use:

$("#element").trigger("change");

Create an Event object and pass it to the dispatchEvent method of the element:

var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);

This will trigger event listeners regardless of whether they were registered by calling the addEventListener method or by setting the onchange property of the element.


By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do.

If you want the event to bubble, you need to pass a second argument to the Event constructor:

var event = new Event('change', { bubbles: true });

Information about browser compability:

  • dispatchEvent()
  • Event()

Tags:

Javascript