1

I want to give the users the ability to change from an input to another using the tab key. However on select2 the tab key is not working. How can I open select2 on focus?

I tried this solution but it's not working.

jsFiddle

$('.js-select').select2({
     placeholder: "Select",
     width: "100%"
}).one('select2-focus', select2Focus).on("select2-blur", function () {
    $(this).one('select2-focus', select2Focus)
})

function select2Focus() {
    var select2 = $(this).data('select2');
    setTimeout(function() {
        if (!select2.opened()) {
            select2.open();
        }
    }, 0);  
}
Community
  • 1
  • 1
brunodd
  • 2,474
  • 10
  • 43
  • 66

3 Answers3

1

I tried a number of approaches in the linked SO question and finally came up with the following that works for me. I am using Select2 4.0.1, the latest as of today. The variable 'element' is the <select> element you have as a Select2.

$.data(element).select2.on("focus", function (e) {
    $(element).select2("open");
});
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
EricksonG
  • 472
  • 4
  • 10
0

I found that MR Lister and EriksonG's solution exactly as written didn't work with select2 4.0.3 (jsfiddle), but slightly modified and cleaned up a little it works very well:

$('.js-select').each(function () {
    var s = $(this);
    s.data().select2.on('focus', function (e) {
        s.select2('open');
    });
});

jsfiddle demo

Gabby Paolucci
  • 887
  • 8
  • 23
0

For those using multiple and select2, the events dont fire quite right and detecting when the select2 is open or focused is very difficult and can lead to infinite recursion.

I ended up hooked into the tab key for the previous field and force it to open. This was the only solution I found to work after a day of trying.

// tab off previous field to select2 multiple
$('.previousFieldToSelect2Multiple').on('keydown', function(e)
{ 
    var keyCode = e.keyCode || e.which; 
    if (keyCode == 9)
    {
        setTimeout(function()
        {
            $('.select2-multiple').select2('open');
        }, 20);
    } 
});
jjxtra
  • 20,415
  • 16
  • 100
  • 140