The reason you’re seeing this behavior is that you are forcing the Select2 open when focus is on the Select2. Select2 returns focus to this element when the dropdown closes, so your focus handler immediately forces it back open.
My suggestion is to remove your focus handler. Normal HTML <select>
controls do not automatically open when they receive focus (especially via the keyboard), but rather when they are selected (i.e., clicked). Since Select2 already opens when it is clicked (or the keyboard equivalent—pressing Enter when the control has focus), you don’t need any special logic at all.
That said, if you really want to make the Select2 open on focus, then you need to add some extra logic to keep it from re-opening when focus returns to it after the dropdown has closed. This code works:
$(function() {
$('select').each(function() {
var field = $(this);
var openOnFocus = true;
field.select2({
minimumResultsForSearch: 5,
width: '7rem'
});
field.on("select2:closing", function () {
openOnFocus = false;
});
field.data('select2').$selection.on('focus', function() {
openOnFocus && field.select2('open');
setTimeout(() => { openOnFocus = true; }, 500);
});
});
});
Note that I had to remove your closeOnSelect
(or selectOnClose
, I don’t recall which one), and put in a small delay before setting the openOnFocus
flag back to true
so the second focus
event (after the dropdown closes) doesn’t trigger the Select2 open method.