Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 540
Kida Avatar asked Jan 30 '26 19:01

Kida


1 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 built on v3.4).

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

      $(document).on('select2:open', () => {
        document.querySelector('.select2-search__field').focus();
      });
like image 98
Kida Avatar answered Feb 02 '26 10:02

Kida