1

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.

dashman
  • 2,674
  • 2
  • 27
  • 46
  • what is it about "the way the field is processed" which means you can't just use `document.getElementById().value`? – Dan O Apr 13 '20 at 14:52
  • yes - it seems like an Angular web page and it accepts each keypress and does something app specific on the 3rd letter - i.e. it's like those airline flight pages - enter the identifier (SFO) and then it displays the full city name automatically (like a combo-box)...but it's an INPUT element. – dashman Apr 13 '20 at 16:29

1 Answers1

0

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.

mgarcia
  • 4,746
  • 3
  • 13
  • 29
  • Just tried that from the Firefox web console and it didn't take – dashman Apr 13 '20 at 16:35
  • It works for me. Maybe you are doing something different? I built [this jsfiddle](https://jsfiddle.net/59zs1jeh/) so you can check it works. – mgarcia Apr 13 '20 at 16:43
  • I don't think I explained my problem clearly. I'm trying to simulate input into the INPUT field. e.g. I'd like to add S-F-O to the input field. I can't assign element.value - see my comment above - doesn't work. – dashman Apr 13 '20 at 17:44
  • In the event listener for the input element, i can do `this.value += ev.key` and it saves it - but it's not triggering the processing event that happens when I input the keys using a keyboard. – dashman Apr 13 '20 at 19:52
  • Tried out at new version of Firefox, still doesn't work... – NNL993 May 23 '22 at 06:20