Selectpicker causes Jquery .on('change') to trigger twice
Asked Answered
R

3

7

When using bootstrap-select selectpicker for <select> lists I am having an issue where it is triggering the on change event twice.

for example here is the my select list

<select class="form-control selectpicker label-picker" data-style="btn-white" data-live-search="true" data-size="10">
    @foreach (var option in property.Options)
    {
        <option value="@option.Value">@option.Label</option>
    }
</select>

and here is my Jquery script

<script>
    $(document).on('change', '.label-picker', function (e) {
        debugger;
    })
</script>

Whenever I change my dropdown it triggers my script twice. When I remove the selectpicker class from my select it will only trigger once. However, I like the style and the built in ability to search dropdowns so I would prefer to use selectpicker.

I have been checking through my code and I only declare bootstrap-select.min.js once. I am adding this select list dynamically, where it is the result of another action in my UI. I wonder if this is part of the issue, but I am not sure why it is only giving the issue when referencing selectpicker.

Any suggestions would be helpful as I am wasting a lot of time on this.

Rorke answered 11/10, 2019 at 20:22 Comment(1)
Guess here, but it looks like select picker has built in functionality and you are wiring up the change event twice by adding the new function, does that make sense?Tavarez
J
5

I don't know how/if you ever resolved this but I ran into it today as well and it seems to be due to using a class-name for the jQuery selector and this class is assigned to the select element as well as the selectpicker wrapper elements, so the event is triggered twice.

There is some discussion around this here: https://github.com/snapappointments/bootstrap-select/issues/1322

Personally I solved it by prefixing the jQuery selector with select -- so it's select.classname -- and that stops it from hooking up the event-handler to the selectpicker wrapper.

And it's worth emphasizing that this is only a problem when using the class-name as the selector; I have never seen any duplicates when using id or anything else...

Joyance answered 29/6, 2020 at 16:47 Comment(0)
H
4

Nothing help me

so at the end I have to do stopImmediatePropagation();

 $(document).on('change', '#label-picker', function (e) {
        / / Respective Code ....


       e.stopImmediatePropagation()

    })
Houseclean answered 9/10, 2020 at 7:57 Comment(0)
E
0

The bootstrap elements are using the same class as you specify and it called twice.so using Inspect element check and find a unique path for selector:

Sample:

<select class="selectpicker myclass">
     <option></option>
     ....
</select>


$(document).on('changed.bs.select', '.my-class select', function () {})
Exhalant answered 15/3, 2021 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.