Home » Jquery » javascript – How to focus bootstrap select picker

javascript – How to focus bootstrap select picker

Posted by: admin February 22, 2020 Leave a comment

Questions:

I’ve use data-live-search for searchable option. When I click on focus button it should focus again select. I’ve use following code

$("#focus").click(function() {
  $(".selectpicker").focus();
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button>

Whenever I press enter t is focus to select box but search option is not shown. I’ve attach screenshot
Please give me suggestion for display proper option with search option when I enter it

How to&Answer:

focus() not working because it turned to customized select not native select option, by the way there is a native way to do this in selectpicker plugin, an event called toggle

$("#focus").click(function() {
  // toggle
  $('.selectpicker').selectpicker('toggle');

  // select by value
  $('.selectpicker').selectpicker('val', 'Test');
  $('.remove-example').selectpicker('refresh');

  // change highlight
  $('.dropdown-menu li').removeClass('active')
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.1/js/bootstrap-select.js"></script>

<select data-live-search="true" data-live-search-style="startsWith" class="selectpicker">
  <option value="4444">4444</option>
  <option value="Fedex">Fedex</option>
  <option value="Elite">Elite</option>
  <option value="Interp">Interp</option>
  <option value="Test">Test</option>
</select>
<button id="focus">focus</button>