How do I programmatically trigger an “input” event without jQuery?

I installed an event handler on an input using

var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});

As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the input event so that my event listener is called?


Solution 1:

The proper way to trigger an event with plain JavaScript, would be to create an Event object, and dispatch it

var event = new Event('input', {
    bubbles: true,
    cancelable: true,
});
  
element.dispatchEvent(event);

Or, as a simple one-liner:

element.dispatchEvent(new Event('input', {bubbles:true}));

FIDDLE

This is not supported in IE, for that the old-fashioned way still has to be used

var event = document.createEvent('Event');
event.initEvent('input', true, true);

elem.dispatchEvent(event);

Solution 2:

element.dispatchEvent(new Event('input'));

Solution 3:

If you are using react, following will work:

const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));