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>
Try this to manually dispatch the event, see EventTarget.dispatchEvent():
inputField.dispatchEvent(new Event("input"))
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With