I'd like to simulate a keypress into an INPUT object.
I can't just set the element value because of the way the field is processed.
Looks like the solution has to do with dispatchEvent
and KeyboardEvent
- but there are so many variations and most deprecated.
What's the current modern way of sending printable characters to an INPUT field.
I'd like to simulate a keypress into an INPUT object.
I can't just set the element value because of the way the field is processed.
Looks like the solution has to do with dispatchEvent
and KeyboardEvent
- but there are so many variations and most deprecated.
What's the current modern way of sending printable characters to an INPUT field.
Share Improve this question asked Apr 13, 2020 at 14:30 dashmandashman 3,0184 gold badges32 silver badges55 bronze badges 3 |2 Answers
Reset to default 16For modern web development dom editing use the following:
const inputElement = document.querySelector("input");
inputElement.value = 'newValue';
inputElement.dispatchEvent(
new Event("input", { bubbles: true, cancelable: true })
);
With modern websites we now need to notify event handlers that the field has been changed, for all/any state management to recognise change. Previously without dispatching event you are just modifying the value field through the DOM.
If you want to simulate a keypress
event you will have to do:
var evt = new KeyboardEvent('keypress', { key: "a" });
input.dispatchEvent(evt);
As you said, the keypress
event is being deprecated and it is not guaranteed to work in the future. It is recommended to use beforeinput
or keydown
instead.
Even so, the support for keypress
is still good, as you can see in here.
document.getElementById().value
? – Dan O Commented Apr 13, 2020 at 14:52