Tom Rudge
Tom Rudge

Reputation: 3272

Turn off autofocus for bootstrap-select / select2

http://www.bootply.com/YAQrE52K6X

    $("#dataCombo").selectpicker({
    multiple:true
    });

    <div class="container">

  <h3>Multiple Select</h3>
  <select id="dataCombo" class="selectpicker" data-live-search="true" multiple="multiple" style="width:400px;">

    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
    <option value="four">Four</option>
    <option value="five">Five</option>
    <option value="six">Six</option>
  </select>

</div>

I want to turn off autofocus so the input does not ask for me to search immediately after clicking the dropdown. Tried to use .blur etc... but nothing so far. Looked around for a fix. Moved to use "bootstrap-select" from "select2" due to same problem. The keyboard on devices appears covering the multiple dropdown items

Upvotes: 3

Views: 4788

Answers (2)

user12914956
user12914956

Reputation:

for bootstrap select picker you can do like this it works for me :

$(document).on("change","select.selectpicker",function(){
    $(this).next().next().children(".bs-searchbox").children("input[type='search']").blur()
});

Upvotes: 0

Dekel
Dekel

Reputation: 62666

I wasn't able to fix this with bootstrap-select (seems like they have some issues with triggering the show.bs.select and shown.bs.select events), but since you also mentioned that you tried this with select2, here is a solution for the select2:

  $("#dataCombo").select2({
    closeOnSelect: false
  });
  $("#dataCombo").on('select2:open', function () {
    $(document.activeElement).blur()
  });

Check this example:
https://jsfiddle.net/yw61h28z/

Update - 2016/12/05

Managed to get it to work (took some time to play with the focus/blur/targets things).

$(document).ready(function() {
  $("#dataCombo").select2({
    closeOnSelect: false
  });
  $("#dataCombo").one('select2:open', function (e) {
    $(document.activeElement).blur()
  });
  $("#dataCombo").on('select2:close', function(e) {
    if ($(event.target).parents('.select2').length) {
      // The closing was done inside the select2 container
    } else {
      $("#dataCombo").one('select2:open', function (e) {
        $(document.activeElement).blur()
      });
    }
  });
});

Here is the update to my original jsfiddle:
https://jsfiddle.net/yw61h28z/4/

Here is the idea behind the code:
1. The first time the select2 is opened - blur the input (but only one time) - this makes sure the select2 menu is opened, but the input isn't focused (so the keyboard is not displayed).
2. On closing the select2 menu - check the element that caused the close.
2.1. If that element is part of the select2 block - ignore it and close keep closing the menu.
2.2 Else - The next time the select2 menu is opened we blur the input (again - only 1 time).

Upvotes: 3

Related Questions