1

I’m using jQuery 1.12. I have a couple of styled select menus on my page. When one is active, I would like to be able to press “Tab” and then have focus shift to the next styled select menu. I’m trying this

return $('div.select-styled:first').keydown(function(e) {
  alert("key pressed");
  if (e.which === 9) {
    $('div.select-styled.active').each(function() {
      return $(this).removeClass('active').next('ul.select-options').hide();
    });
    return $('div.select-styled:second').focus().click();
  }
});

but nothing’s happening. You can see from my Fiddle — http://jsfiddle.net/cwzjL2uw/5/ , that you can click “Tab” on the last name field and the first styled select menu is activated, but then clicking “Tab” a second time does nothing. How do I capture the keypress event from my styled select menu?

Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

1

The styled select element is implemented via an div element, which cannot get focus unless is has a tabindex attribute. You can set the tabindex to -1 if you want an element to become focusable.

For your code, the wrapper can be set to following:

var $wrapper = $("<div />", {
  'class': "select",
  'tabindex': '-1'
})

Then your code may work as your expectation.

However, the tab focus is already a basic functionality that borwser provides, which means that instead of listening to the tab key event, you should listen to focus and blur event and update the representation of your control. In this case, you should set the tabindex to 1, and add event handler. Then you can remove the keydown event listener as well as the listener on body to detect the lost of focus.

Here is the updated fiddle you can check: JS Fiddle

See also:

Community
  • 1
  • 1
Jack Q
  • 301
  • 1
  • 2
  • 9
  • Besides, you need to use `nth-child(2)` to select the second `select` element instead of `second`. – Jack Q Dec 31 '16 at 04:11
  • Thanks for this. Although it works great on Chrome (I can tab from one menu to the next), on Firefox I can't tab from one menu to the next. Is tehre a way to make this code cross-browser -- at least have it work on both Chroem and Firefox? – Dave Dec 31 '16 at 19:54
  • Updated the code ([fiddle](http://jsfiddle.net/cwzjL2uw/8/)) and set the `tabindex` of both `input` and styled `select` to `1`. Thus firefox will iterate the focus in these elements. – Jack Q Jan 01 '17 at 04:20