Ynhockey
Ynhockey

Reputation: 3932

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?

Upvotes: 2

Views: 4208

Answers (2)

Ilya Yarkovets
Ilya Yarkovets

Reputation: 840

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

Upvotes: 3

BassT
BassT

Reputation: 849

Have you considered using the .off function? You could remove the event handler (causing the infinite loop), changing the state of the switches and then attaches the handler back on.

Upvotes: 0

Related Questions