Bootstrap Switch - Change state after clicking on button

brunodd picture brunodd · Jul 10, 2015 · Viewed 26.1k times · Source

I am using Bootstrap Switch plugin and Bootstrap Modal. Once the user clicks to change the Switch from on to off the Modal box fades in asking for a confirmation.

How do I change the Switch from on to off or from off to on only after the user clicks on Confirm button? If the user clicks on Cancel then the Switch should go back to Off status.

My code

$("#myswitch").bootstrapSwitch();

$('#myswitch').on('switchChange.bootstrapSwitch', function (e, data) {

    $('#showModal').modal({
     backdrop: 'static',
     keyboard: false
 });
});

Answer

Maxime Peloquin picture Maxime Peloquin · Jul 10, 2015

You can use the state method to prevent the switch from changing. Remember to use the third parameter to make sure the event is not executed again.

    $('#myswitch').bootstrapSwitch('state', !data, true);

Working example :

https://jsfiddle.net/hL0as0mv/169/

Full documentation : http://bootstrapswitch.site/methods.html