Reputation: 2584
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.
$('.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);
}
Upvotes: 1
Views: 5551
Reputation: 21180
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);
}
});
Upvotes: 0
Reputation: 927
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');
});
});
Upvotes: 0
Reputation: 472
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");
});
Upvotes: 1