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
Probably after the selection is made a select2-focus event is triggered.
The only way I found is a combination of select2-focus and select2-blur event and the jQuery one event handler.
So the first time the element get the focus, the select2 is opened for one time (because of one), when the element is blurred the one event handler is attached again and so on.
Code:
$('#test').select2({
data: [{
id: 0,
text: "enhancement"
}, {
id: 1,
text: "bug"
}, {
id: 2,
text: "duplicate"
}, {
id: 3,
text: "invalid"
}, {
id: 4,
text: "wontfix"
}],
width: "300px"
}).one('select2-focus', select2Focus).on("select2-blur", function () {
$(this).one('select2-focus', select2Focus)
})
function select2Focus() {
$(this).select2('open');
}
Demo: http://jsfiddle.net/IrvinDominin/fnjNb/
To let the mouse click work you must check the event that fires the handler, it must fire the open method only if the event is focus
Code:
function select2Focus() {
if (/^focus/.test(event.type)) {
$(this).select2('open');
}
}
Demo: http://jsfiddle.net/IrvinDominin/fnjNb/4/
select2 v 4.0 has changed its API's and dropped the custom events (see https://github.com/select2/select2/issues/1908). So it's necessary change the way to detect the focus on it.
Code:
$('.js-select').select2({
placeholder: "Select",
width: "100%"
})
$('.js-select').next('.select2').find('.select2-selection').one('focus', select2Focus).on('blur', function () {
$(this).one('focus', select2Focus)
})
function select2Focus() {
$(this).closest('.select2').prev('select').select2('open');
}
Demo: http://jsfiddle.net/IrvinDominin/xfmgte70/