I am using Select 2 4.0.13 on jQuery 3.6.1 and am looking for a way to allow the search bar to be selected when the Select 2 is opened.
I found https://stackoverflow.com/a/67691578/1278201 which does exactly what I need (and works when there are multiple select 2 on the page) however it "only" works when the select2 has an ID - if it just has a unique name/class then it does not work as the ID is blank
$(document).on('select2:open', (e) => {
const selectId = e.target.id
$(".select2-search__field[aria-controls='select2-" selectId "-results']").each(function (
key,
value,
){
value.focus();
})
})
Looking at the markup, when the select2 has an ID of IDHERE it adds to each Select 2:
aria-owns="select2-IDHERE-results"
When there is no ID then this aria-owns is added using the name but with a "random" value included
aria-owns="select2-SELECTNAME-p5-results"
where P5 seems to random (i.e. another select 2 will use fu in place of p5 and so on.
Looking in the console, e returns both a target.name and a target.dataset.select2Id element but I cannot get any of those to work
Can another attribute be used to do this and target the relevant select 2 when the ID is not present and there are multiple select 2 on the same page?
CodePudding user response:
The easiest way is to give it a (random) id. I had the problem too and for me this was the easiest way. (I´m using v4.1.0-rc)
function random() {
return crypto.getRandomValues(new BigUint64Array(1))[0].toString(16);
}
$(".myselect:not(.select2-hidden-accessible)").attr('id', random()).select2()
$(document).on('select2:open', function(e) {
document.querySelector(`[aria-controls="select2-${e.target.id}-results"]`).focus();
});
I dynamically create select2 fields, if you have several at once you can call it with a each
.
CodePudding user response:
A possible solution is:
$(document).on('select2:open', function (e) {
document.querySelector('.select2-container--open .select2-search__field').focus();
})
The snippet:
$('.js-example-basic-single').select2();
$(document).on('select2:open', function (e) {
document.querySelector('.select2-container--open .select2-search__field').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select name="state">
<option value="AL">Alabama 111</option>
<option value="WY">Wyoming 111</option>
</select>
<select name="state">
<option value="AL">Alabama 222</option>
<option value="WY">Wyoming 222</option>
</select>