Keep focus on multiple Select2 dropdown

Hi All

Apologies if this is a repeat question but I can’t seem to find the answer to this in the forums or by Googling. I’d be surprised if this hasn’t been asked before though, and I’ll probably find it after I post this but here goes anyway :slight_smile:

So I’ve got a Select2 up and running and it’s set to allow multiple value selections. Users are reporting though that when they make a selection the Select2 isn’t keeping the focus on the textbox so they’re having to click it again in order to add another option. That’s getting frustrating for them as they’re expecting to just keep typing.

Looking at the documentation I can see there’s an “open” event and I’ve added this to my custom “change” event expecting it to place the focus instantly back into the textbox but that only seems to work when I have single value mode switched on. The moment multiple is enabled it no longer runs the open event.

Does anyone have any suggestions on how I can get multiple value mode to keep the focus?

Thanks
James

P.S. The same really applies as well to on page load.

A bit of a small update:

I’ve now added the closeOnSelect parameter and although that keeps the dropdown options on screen the focus is still coming off the textbox the moment I select an option. Ideally I want the focus to remain so I can edit the search term without having to pick up my mouse, click the box and then type the search again.

Hope that makes sense.

Which version of Select2 are you using? The example multi-select on the Select2 site keeps focus on the text area as as the user makes multiple selections—exactly what you want.

Hi John

It was 4.0.7 but I’ve just upgraded it to 4.0.10 this morning and that’s solved the focus issue when making a selection, thank you!

The only thing I can’t get working now is focus on page load. I can see the cursor briefly appearing as the Select2 first loads but we add some default values to the textbox, passed in through a query string, so the moment Select2 initialises those it removes the focus.

I’ve had a look through the various events and tried triggering an open and focus at the end of my script but Select2 is just ignoring them. Annoyingly if I open up a console tab in the browser after it’s loaded and trigger an “open” it applies the focus fine so there must be a delay happening somewhere.

Yes, it’s been my experience that you need to call your programmatic open code after a small delay. I recommend putting it in a setTimeout() call with a delay of about 250ms. Do that after all of your other initializing, and it should work for you.

1 Like