Houy Narun
Houy Narun

Reputation: 1715

Select2 V.4: Search box is not got focus on open

I using select2 for my project for the first time, and I thought I met many of my project requirements. However, one thing it was not is on their search box.

When I click on select2 element, the dropdown was opened but I could not type anything in their input box unless I click on their search.

Here is my sample code:

$(document).ready(function() {
  $('.js-example-basic-single').select2({
    width: 370
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/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 class="js-example-basic-single" name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>

By inspecting issue console, it did not show any related issues at all, why it did not work well as expected ? Please kindly help, thanks.

Upvotes: 2

Views: 4249

Answers (2)

Tharaka Devinda
Tharaka Devinda

Reputation: 1

$(document).ready(function () {
  $("#size_id").select2({
    placeholder: "Select a size", // Add a placeholder if needed
    allowClear: true, // Optional: allows clearing the selection
  });

  // Add an event listener for the "open" event
  $("#size_id").on("select2:open", function () {
    // Target the search input field in Select2 and focus on it
    document.querySelector(".select2-search__field").focus();
  });
});

Replace your search Id with the size_id , cheers !!!

Upvotes: 0

Muhammad Asif
Muhammad Asif

Reputation: 516

Dear there is a conflict in jquery 3.5.X with select2, I have added one small fix, kindly use the below jquery code in order to fulfill your requirement.

$(document).ready(function() {
  $('.js-example-basic-single').select2({
    width: 370
  });       
});
$(document).on('select2:open', () => {
    document.querySelector('.select2-search__field').focus();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/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 class="js-example-basic-single" name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>

Upvotes: 4

Related Questions