Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating keypress into an INPUT field (Javascript)

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.

like image 294
dashman Avatar asked Jul 15 '26 02:07

dashman


2 Answers

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.

like image 150
Shimsho Avatar answered Jul 17 '26 14:07

Shimsho


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.

like image 31
mgarcia Avatar answered Jul 17 '26 14:07

mgarcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!