How to Auto Focus Select2 on Page Load?

I’m using Select2, and I want to automatically set focus on the search field when the page loads. How can I achieve this using jQuery and Select2?

Here’s the code I’m using:

<select id="my-select2">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
$(document).ready(function() {
    $('#my-select2').select2('focus').trigger('click');
});

but the code above is not working.

Use this line below. You can find this information in their official documentation.

$('#my-select2').select2('open');`

According to the Select2 documentation, this code is all you need to open and focus the select2.