Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto trigger input event programmatically on input text field?

Tags:

javascript

As you can see in the code section below, once you click on one the buttons the text in the field changes but the event does not get fired (and it does not run alertTextInput() method), when you type text directly under the text field the event is triggered as expected.

How can I activate the event manually by using a code or using a method that changes the text and triggers the event? thank you!

const changeTextButton = document.querySelector("#change-text");
const clearButton = document.querySelector("#clear");
const inputField = document.querySelector("#query");

changeTextButton.addEventListener("click", changeText);
clearButton.addEventListener("click", clear);
inputField.addEventListener("input", alertTextInput);

function changeText() {
  inputField.value = "Demo Text!!";
  inputField.dispatchEvent(new Event("input"))
}

function clear() {
  inputField.value = "";
  inputField.dispatchEvent(new Event("input"))
}

function alertTextInput() {
  alert(inputField.value);
}
<input type=text id="query">
<button id="change-text">Change the text programmatically</button>
<button id="clear">Clear</button>
like image 718
Sagi Nadav Avatar asked Mar 19 '18 17:03

Sagi Nadav


Video Answer


2 Answers

Try this to manually dispatch the event, see EventTarget.dispatchEvent():

inputField.dispatchEvent(new Event("input"))
like image 58
viz Avatar answered Oct 16 '22 11:10

viz


From React Doc

React expects to hear the input event

So trigger the input event after set the value. This is how to trigger.

The Final code is:

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

inputElement.value = '0.2'
inputElement.dispatchEvent(event);
like image 23
hzwzw Avatar answered Oct 16 '22 10:10

hzwzw