Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 open dropdown on focus

I have a form with multiple text inputs and some select2 elements. Using the keyboard to tab between fields works fine - the Select2 element behaves like a form element and receives focus when tabbing. I was wondering if it is possible to open the dropdown when the Select2 element gets focus.

Here's what I've tried so far:

$("#myid").select2().on('select2-focus', function(){      $(this).select2('open'); }); 

But using this code makes the dropdown to open again after a selection is made.

like image 335
andreivictor Avatar asked Jan 08 '14 07:01

andreivictor


People also ask

How do you open the Select 2 on Ford Focus?

This solution works fine for keyboard navigation. But I found a bug: on mouse click on select2 element, it needs two clicks to open the dropdown: the first click will make focus on element and the second will actually open the dropdown.

How do you focus a dropdown in HTML?

The <select> autofocus attribute is a boolean attribute that specifies that the drop-down list should automatically get focus when the page loads.

How do I know if select2 is open?

select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented. select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.

How do I stop select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.


1 Answers

Working Code for v4.0+ *(including 4.0.7)

The following code will open the menu on the initial focus, but won't get stuck in an infinite loop when the selection re-focuses after the menu closes.

// on first focus (bubbles up to document), open the menu $(document).on('focus', '.select2-selection.select2-selection--single', function (e) {   $(this).closest(".select2-container").siblings('select:enabled').select2('open'); });  // steal focus during close - only capture once and stop propogation $('select.select2').on('select2:closing', function (e) {   $(e.target).data("select2").$selection.one('focus focusin', function (e) {     e.stopPropagation();   }); }); 

Explanation

Prevent Infinite Focus Loop

Note: The focus event is fired twice

  1. Once when tabbing into the field
  2. Again when tabbing with an open dropdown to restore focus

focus menu states

We can prevent an infinite loop by looking for differences between the types of focus events. Since we only want to open the menu on the initial focus to the control, we have to somehow distinguish between the following raised events:

event timeline

Doing so it a cross browser friendly way is hard, because browsers send different information along with different events and also Select2 has had many minor changes to their internal firing of events, which interrupt previous flows.

One way that seems to work is to attach an event handler during the closing event for the menu and use it to capture the impending focus event and prevent it from bubbling up the DOM. Then, using a delegated listener, we'll call the actual focus -> open code only when the focus event bubbles all the way up to the document

Prevent Opening Disabled Selects

As noted in this github issue #4025 - Dropdown does not open on tab focus, we should check to make sure we only call 'open' on :enabled select elements like this:

$(this).siblings('select:enabled').select2('open');

Select2 DOM traversal

We have to traverse the DOM a little bit, so here's a map of the HTML structure generated by Select2

Select2 DOM

Source Code on GitHub

Here are some of the relevant code sections in play:

.on('mousedown' ... .trigger('toggle')
.on('toggle' ... .toggleDropdown()
.toggleDropdown ... .open()
.on('focus' ... .trigger('focus'
.on('close' ... $selection.focus()

It used to be the case that opening select2 fired twice, but it was fixed in Issue #3503 and that should prevent some jank

PR #5357 appears to be what broke the previous focus code that was working in 4.05

Working Demo in jsFiddle & Stack Snippets:

$('.select2').select2({});    // on first focus (bubbles up to document), open the menu  $(document).on('focus', '.select2-selection.select2-selection--single', function (e) {    $(this).closest(".select2-container").siblings('select:enabled').select2('open');  });    // steal focus during close - only capture once and stop propogation  $('select.select2').on('select2:closing', function (e) {    $(e.target).data("select2").$selection.one('focus focusin', function (e) {      e.stopPropagation();    });  });
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"></script>    <select class="select2" style="width:200px" >    <option value="1">Apple</option>    <option value="2">Banana</option>    <option value="3">Carrot</option>    <option value="4">Donut</option>  </select>

Tested on Chrome, FF, Edge, IE11

like image 157
KyleMit Avatar answered Sep 20 '22 07:09

KyleMit