最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

keyboard events - Simulating keypress into an INPUT field (Javascript) - Stack Overflow

programmeradmin1浏览0评论

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
  • what is it about "the way the field is processed" which means you can't just use document.getElementById().value? – Dan O Commented Apr 13, 2020 at 14:52
  • 1 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 Commented Apr 13, 2020 at 16:29
  • Take a look at this answer – aljgom Commented Jun 29, 2022 at 21:49
Add a comment  | 

2 Answers 2

Reset to default 16

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.

发布评论

评论列表(0)

  1. 暂无评论