How to focus on first option with tab key with Select2 dropdown

I have a select2 dropdown with a search box. Currently, when tabbing and hitting ENTER, the focus is on search box which is the default behavior in select2.

It currently looks like this and the focus is on the search box after the dropdown is opened :
Image Link

However, when I press the TAB key after the dropdown opens, I want to focus on the first option in the search results list. I have this code for listening TAB key on the page, but it only doesn’t listen for “select2-results__option” even if I put tabindex = 0 into the option tag. Is it possible to achieve this ? I need to select the first “select2-results__option” after pressing the KEY tab.

$(document).on('keyup', '.secondary-overlay-trigger', e => {
        e.stopPropagation();
        if (e.keyCode === KEY_TAB) {
            $('#root, #wrapper, .cel-Faq, .checkout-login-page').addClass('cel-container--has-focus');
        }
    });

Thanks !

Pressing Enter already selects the first item in the dropdown. Why do you need to select it when you press Tab (which isn’t a key that’s normally used to select an item). If you mean you want to highlight the first option when you press Tab, the first matching option should already be highlighted, so again it’s not clear to me why you need to do this with the Tab key.

Note that, according to the WAI-ARIA Authoring Practices web site, the Tab key is not expected to be used to shift focus to the dropdown (that’s the function of the Down Arrow key, which works as expected in a Select2 widget).

1 Like

Hello ! Thanks a lot for your answer. To be sure, I want to highlight the first option in the dropdown. If you look at the image URL, the focus first goes to search box, and the first option is not highlighted. I saw many examples about this and the focus is on the first option by default but what can be the possible reasons for my case ?

Without seeing your code, I can’t say why your first option is not highlighted by default. Are you using placeholder text? If so, I think that requires an empty <option> element as the first item in the <select>. That would explain why the first visible item isn’t selected. But that’s just a guess, since I haven’t seen your actual code.

Can you post your code somewhere like Codepen or JSFiddle?