Search code examples
jquerybootstrap-switch

Bootstrap Switch manual switch event


I am using Bootstrap Switch, and needed to make an exclusive select: there are a bunch of switchers (unknown amount), and the user can turn one just one at a time.

I did something like this:

$('.switcher').on('switchChange.bootstrapSwitch', function() {
    $(".switcher[id!='"+selected_id+"']").each(function() {
        $(this).bootstrapSwitch('state', false);
    });
    $('#'+selected_id).bootstrapSwitch('state', current_state);
});

Unfortunately, this sends the script on an infinite loop (upon state change). I think this is because under the hood, Bootstrap Switch uses a trigger() function, so when the switch state is changed to false, it triggers the switchChange event again, and so on.

I made a workaround, by triggering:

$("#some-container .bootstrap-switch-container *").click(function() {
    // ...
});

Instead. However, this seems like a really really bad solution.

Is there a better way?


Solution

  • Run into same problem yesterday. Solution was found in documentation. In your case you must provide 3rd parameter set to false:

    $('#'+selected_id).bootstrapSwitch('state', current_state, true);
    

    This parameter (named skip) must be provided and set to true when you don't need to trigger switchChange event(-s).