1

I have a select element in my HTML:

<select id="dropdown">
    <option value="1">First</option>
    <option value="2">Second</option>
</select>

It renders as a drop-down menu, which, when the user clicks it, (surprise!) drops down. In order for the page to be used via keyboard only, I wish to make it so that the menu drops down when the user presses a key.

$('body').keypress(function(event) {
    var key = String.fromCharCode(event.which);
    if (key == 'a') {
        $('#dropdown').doSomething(); // ?
    }
});

The best I've found is to invoke focus(). It allows to select the value via keyboard, but it doesn't drop down the menu. Is there a way to make the menu drop down?

cssyphus
  • 37,875
  • 18
  • 96
  • 111
Arry
  • 895
  • 1
  • 7
  • 20
  • Not sure if this is possible: http://stackoverflow.com/questions/360431/can-i-open-a-dropdownlist-using-jquery -- There's always a few other threads trying, but it always seems to come up empty. – tymeJV Aug 20 '13 at 21:09
  • 1
    AFAIK Not possible. Selects need the direct user interaction. Although you can fake your select box using standard elements – Roko C. Buljan Aug 20 '13 at 21:10
  • 2
    possible duplicate of [How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?](http://stackoverflow.com/questions/249192/how-can-you-programmatically-tell-an-html-select-to-drop-down-for-example-due) and http://stackoverflow.com/questions/430237/is-it-possible-to-use-js-to-open-an-html-select-to-show-its-option-list – j08691 Aug 20 '13 at 21:12
  • Thank you all for quick responses, I didn't find out this question was already answered by cursory search before asking. – Arry Aug 20 '13 at 21:19
  • If all you want is to allow keyboard navigation, all major browsers support expanding the dropdown. Alt + down arrow works on Firefox and supposedly IE, Enter or Space on Chrome and other Webkit browsers. – Paulo Almeida Aug 20 '13 at 22:19

1 Answers1

2

Using Chrome browser (28.0) you can force a mouse event like this:

var e = document.createEvent("MouseEvents");
e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
$("#dropdown").get(0).dispatchEvent(e);

See this working demo do not forget to click on body before pressing 'a' to give focus to it

letiagoalves
  • 11,224
  • 4
  • 40
  • 66