<script>
function setFocusToSearchTextField() {
// focus event (ex. tab btn): open the menu
$(document).on('focus', '.select2-selection.select2-selection--single', function () {
// do not open menu, if field is disable for editing
if ($(this).attr('aria-disabled') === "true") {
return
}
const aria_labelledby_container = this.getAttribute("aria-labelledby")
// returns more than one for datetime widget (hours and minutes, both container are on the same html lvl)
// so the only way how to detect the correct one is to use data from attribute
let menu_containers = $(this).closest(".select2-container").siblings('select:enabled')
if (menu_containers.length > 1) {
menu_containers.each(function(){
// find according container
if (aria_labelledby_container.includes(this.id)) {
$(this).select2('open')
}
})
return
}
menu_containers.select2('open')
})
// menu open event: focus on search field if such one exists
$(document).on('select2:open', function (e) {
window.setTimeout(function() {
$(".select2-container--open .select2-search__field").get(0).focus();
}, 200);
});
}
</script>