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?

5
  • Not sure if this is possible: stackoverflow.com/questions/360431/… -- There's always a few other threads trying, but it always seems to come up empty. Commented Aug 20, 2013 at 21:09
  • 1
    AFAIK Not possible. Selects need the direct user interaction. Although you can fake your select box using standard elements Commented Aug 20, 2013 at 21:10
  • 2
    possible duplicate of How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)? and stackoverflow.com/questions/430237/… Commented Aug 20, 2013 at 21:12
  • Thank you all for quick responses, I didn't find out this question was already answered by cursory search before asking. Commented Aug 20, 2013 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. Commented Aug 20, 2013 at 22:19

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.