bootstrap-select does not proxies click event

2019-06-22 16:12发布

问题:

I had select element:

  <select id='selectBox'>
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

and set click event via jquery:

$('#selectBox option').click(function(){
.....
});

after using http://silviomoreto.github.io/bootstrap-select/ :

  <select id='selectBox' class="selectpicker" multiple="" data-selected-text-format="count">
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

I got nice multiply dropdown and all work fine except that when I click on menu item (select or delestct it) nothing happends.

Why not click event proxies from my original (which was hided) option element to the new created element 'ul.dropdown-menu li a' ? How can I fix it?

回答1:

Change you code to:

$('#selectBox').on('change', function(){
    .....
});

this must work;



回答2:

While $("#selectBox").change(...) / .on("change", ...) fire when the dropdown menu option changes, it will not work when the selection stays the same.

If you want to e.g. check a radio button associated with the dropdown menu as soon as the dropdown closes, use the hidden.bs.select event.

We could also use the related show.bs.select or shown.bs.select as long as we do not cause the dropdown to lose focus and close.

The drawback is that we get the event even if we do not change the dropdown menu selection, e.g. by opening and then clicking outside the dropdown without selecting an option.

See bootstrap-select documentation on events.