最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How do i open a <select> menu in by pressing enter on keyboard - Stack Overflow

matteradmin5PV0评论

For a menu in html, clicking on the select will show the drop down with options, but how would I trigger this by clicking on the enter key. I have tried setting up a keyup listener which would then trigger the 'click' event, but the menu is not showing up

For a menu in html, clicking on the select will show the drop down with options, but how would I trigger this by clicking on the enter key. I have tried setting up a keyup listener which would then trigger the 'click' event, but the menu is not showing up

Share Improve this question asked May 19, 2019 at 23:24 Tenzin ChoklangTenzin Choklang 5232 gold badges5 silver badges24 bronze badges 1
  • This is not currently possible unfortunately: stackoverflow./questions/6992639/… – aprouja1 Commented May 19, 2019 at 23:44
Add a ment  | 

2 Answers 2

Reset to default 1

Why not try an easier approach? Select opens when you hit enter when it has focus on it, so basically you need only to autofocus when the page load. Example:

<select id="dropdown" autofocus class="" name="">
 <option value="">Opt1</option>
 <option value="">Opt2</option>
 <option value="">Opt3</option>
</select>

If you still want to trigger the event EVERY time enter is hitted, you can do this:

window.addEventListener('keypress', function (e) {
 if (e.keyCode == 13) {
  document.getElementById("dropdown").focus();
 }
}, false);

Basically, select gain focus when you hit enter, then you can hit again to open it.

To answer my own question, the options are opened by using either the up/down arrow keys once the field is in focus. Its something that is build in the html, so no need to create separate listeners for it

Post a comment

comment list (0)

  1. No comments so far