'How do i open a <select> menu in by pressing enter on keyboard
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
Solution 1:[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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Federico Provenziani |
| Solution 2 | Tenzin Choklang |
