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

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

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 }));

Solution 4 - Javascript

Try this code

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

elem.dispatchEvent(event);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbdeshamView Question on Stackoverflow
Solution 1 - JavascriptadeneoView Answer on Stackoverflow
Solution 2 - JavascriptRedDragonWebDesignView Answer on Stackoverflow
Solution 3 - JavascriptLahiru ChandimaView Answer on Stackoverflow
Solution 4 - JavascriptAntare74View Answer on Stackoverflow