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.
For 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.
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