Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 772
bdesham Avatar asked Feb 26 '16 18:02

bdesham


People also ask

How do you trigger an input event?

Use the dispatchEvent Method querySelector('input'); element. addEventListener('change', () => console. log('change')) const event = new Event('change'); element. dispatchEvent(event);

How do you trigger a change event?

Like an Apex trigger for Salesforce objects, you define a change event trigger on the change event corresponding to the Salesforce object. Only after insert triggers are supported. Define a change event trigger with the after insert keyword on the change event using this format.


1 Answers

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); 
like image 200
adeneo Avatar answered Oct 14 '22 20:10

adeneo