Search code examples
jquerytwitter-bootstrapscrollanchorbootstrap-selectpicker

Selectpicker (bootstrap-select) unfocus onchange


I am using an hidden anchor to unfocus a bootstrap select on change like this:

HTML:

<select id="SelectAddress" name="SelectAddress" class="selectpicker" title="Select an address" data-header="Select an address">
    <option id="1" value="1" selected >First address</option>
    <option id="2" value="2"  >Second address</option>
</select>

jQuery:

$("#SelectAddress").on("change", function() {
//...mycode...
  $("#AFocus").focus();
});

The $("#AFocus").focus(); makes unfocus the select picker but it also makes the to page go up. AFocus is at the top of page, so...

How to unfocus a select picker without using an anchor tag like my AFocus without scrolling the page ?

Here is an example: http://jsfiddle.net/ya0o7hzb/ Scroll down the page to see the bootstrap-select.


Solution

  • bootstrap-select will add some HTML in the DOM like this:

        <div class="btn-group bootstrap-select">
    <button type="button" class="btn dropdown-toggle btn-default" data-toggle="dropdown" role="button" data-id="SelectAddress" title="Address 1" aria-expanded="false">
    <span class="filter-option pull-left">
    Address 1</span>
    &nbsp;<span class="bs-caret">
    <span class="caret">
    </span>
    </span>
    </button>
    <div class="dropdown-menu open" role="combobox" style="padding-top: 0px; max-height: 297px; overflow: hidden; min-height: 37px;">
    <div class="popover-title">
    <button type="button" class="close" aria-hidden="true">
    ×</button>
    Select an address</div>
    <ul class="dropdown-menu inner" role="listbox" aria-expanded="false" style="max-height: 248px; overflow-y: auto; min-height: 0px;">
    <li data-original-index="1" class="selected">
    <a tabindex="0" class="" data-tokens="null" role="option" aria-disabled="false" aria-selected="true">
    <span class="text">
    Address 1</span>
    <span class="glyphicon glyphicon-ok check-mark">
    </span>
    </a>
    </li>
    <li data-original-index="2" class="">
    <a tabindex="0" class="" data-tokens="null" role="option" aria-disabled="false" aria-selected="false">
    <span class="text">
    Address 2</span>
    <span class="glyphicon glyphicon-ok check-mark">
    </span>
    </a>
    </li>
    </ul>
    </div>
    <select id="SelectAddress" name="SelectAddress" class="selectpicker" title="Select an address" data-header="Select an address" onchange="blur_picker('SelectAddress')" tabindex="-98">
    <option class="bs-title-option" value="">
    Select an address</option>

    So you have to blur() the button containing the class btn:

    $(".btn").blur();
    

    Working example: http://jsfiddle.net/93ohvn0j/