2

I'm trying to simulate pressing the Enter key on an input field with Javascript so that the input field would get submitted as if the user pressed Enter on the keyboard. I'm using the newest version of Chrome (version 87.0.4280.88).

For example, I can submit the search field in Youtube by entering this code in the console:

document.querySelector("input#search").dispatchEvent(new KeyboardEvent("keydown", {keyCode: 13}))

It works, but uses the deprecated property "keyCode". If I replace keyCode: 13 with key: "Enter", the code just returns True without submitting the search. Why is this, given that the key property is recommended to be used instead of the keyCode one?

There are many posts on stackoverflow addressing this subject, but the offered code snippets that are supposed to simulate Enter key press just don't seem to work in many websites in my experience. What could be the reason behind this?

drublor
  • 21
  • 2
  • I'm going to suggest you check out this older topic which seems to cover your question with lots of detail: https://stackoverflow.com/questions/35394937/keyboardevent-keycode-deprecated-what-does-this-mean-in-practice If you need any additional help, please add more code showing what you have tried when using key: 'enter', I can't tell if you used event.key or something else. – SteveB Dec 27 '20 at 16:34

0 Answers0