Why is jQuery-select2 autofocus not working and how do I fix it?

Viewed 4724

I'm using select2 in all my projects and it works fine. But in my new project, my select2 input doesn't focus as it should. I have to click on it to focus. What can the problem be and how can I fix it?

I don't know which part of code to show, because I didn't change anything in the standard select2 functions.

2 Answers

After hard research, I found the reason and the solution on a GitHub page.

The reason certainly is that I'm using a new version of jQuery 3.6 in this project (others were build on v3.4).

The solution (it's enough to add this JavaScript code):

      $(document).on('select2:open', () => {
        document.querySelector('.select2-search__field').focus();
      });

updated answer for those who have multiple select, this way you will be sure to select to focus the right input

$(document).on('select2:open', function(e) {
  document.querySelector(`[aria-controls="select2-${e.target.id}-results"]`).focus();
});
Related