The current answer is only applicable to versions 3.5.4 and before, where select2 fired blur and focus events (select2-focus
& select2-blur
). It attaches a one-time use handler using $.one
to catch the initial focus, and then reattaches it during blur for subsequent uses.
$('.select2').select2({})
.one('select2-focus', OpenSelect2)
.on("select2-blur", function (e) {
$(this).one('select2-focus', OpenSelect2)
})
function OpenSelect2() {
var $select2 = $(this).data('select2');
setTimeout(function() {
if (!$select2.opened()) { $select2.open(); }
}, 0);
}
I tried both of @irvin-dominin-aka-edward's answers, but also ran into both problems (having to click the dropdown twice, and that Firefox throws 'event is not defined').
I did find a solution that seems to solve the two problems and haven't run into other issue yet. This is based on @irvin-dominin-aka-edward's answers by modifying the select2Focus function so that instead of executing the rest of the code right away, wrap it in setTimeout.
$('.select2').select2({})_x000D_
.one('select2-focus', OpenSelect2)_x000D_
.on("select2-blur", function (e) {_x000D_
$(this).one('select2-focus', OpenSelect2)_x000D_
})_x000D_
_x000D_
function OpenSelect2() {_x000D_
var $select2 = $(this).data('select2');_x000D_
setTimeout(function() {_x000D_
if (!$select2.opened()) { $select2.open(); }_x000D_
}, 0); _x000D_
}
_x000D_
body {_x000D_
margin: 2em;_x000D_
}_x000D_
_x000D_
.form-control {_x000D_
width: 200px; _x000D_
margin-bottom: 1em;_x000D_
padding: 5px;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
select {_x000D_
border: 1px solid #aaa;_x000D_
border-radius: 4px;_x000D_
height: 28px;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>_x000D_
_x000D_
_x000D_
<div class="form-control">_x000D_
<label for="foods1" >Normal</label>_x000D_
<select id="foods1" >_x000D_
<option value=""></option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Carrot</option>_x000D_
<option value="4">Donut</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="form-control">_x000D_
<label for="foods2" >Select2</label>_x000D_
<select id="foods2" class="select2" >_x000D_
<option value=""></option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Carrot</option>_x000D_
<option value="4">Donut</option>_x000D_
</select>_x000D_
</div>
_x000D_