问题
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
回答1:
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 theinput
(but only one time) - this makes sure the select2 menu is opened, but theinput
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 theselect2
block - ignore it and close keep closing the menu.
2.2 Else - The next time the select2 menu is opened weblur
theinput
(again - only 1 time).
来源:https://stackoverflow.com/questions/40509189/turn-off-autofocus-for-bootstrap-select-select2