Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus to search text field when we click on select 2 drop down

I am using select2.js Version: 3.4.3 with bootstrap I have one drop down.

enter image description here

When I click on drop down i got list with search text fields. But I my cursor not focused on search text fields. enter image description here

<form:select path="yearAge" id="yearAgeId"
    cssClass="form-control search-select static-select">
    <form:option value="">Years</form:option>
    <c:forEach var="i" begin="1" end="125"  >
    <form:option value="${i}" label="${i}"></form:option>
    </c:forEach>     
</form:select>


$(".search-select.static-select").select2({
    placeholder: $(this).attr('placeholder'),
    allowClear: true
});

When I click on dropdown cursor focus should set to search text field automatically .

Thank you...!!!!!

like image 769
user3386877 Avatar asked Sep 17 '14 05:09

user3386877


People also ask

What select2 dropdown?

By default, Select2 will attach the dropdown to the end of the body and will absolutely position it to appear above or below the selection container. Select2 will display the dropdown above the container if there is not enough space below the container, but there is enough space above it.


2 Answers

If jQuery 3.6.0 is causing this you can use this:

 $(document).on('select2:open', () => {
    document.querySelector('.select2-search__field').focus();
  });
like image 78
Hammad Ahmed khan Avatar answered Sep 18 '22 23:09

Hammad Ahmed khan


Tested and worked with jQuery 3.6.0:

$(document).on("select2:open", () => {
  document.querySelector(".select2-container--open .select2-search__field").focus()
})
like image 21
Khribi Wessim Avatar answered Sep 21 '22 23:09

Khribi Wessim