Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 510
A. Hasemeyer Avatar asked Oct 11 '19 20:10

A. Hasemeyer


2 Answers

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...

like image 78
Christopher King Avatar answered Nov 07 '22 19:11

Christopher King


Nothing help me

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

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


       e.stopImmediatePropagation()

    })
like image 25
BJ Patel Avatar answered Nov 07 '22 20:11

BJ Patel