Bootstrap Toggle: One on the rest off

I am using the Bootstrap Toggle plugin which converts checkboxes into toggle buttons.

When I change the toggle state from off to on, I want all others to toggle off.

<input type="checkbox" checked data-toggle="toggle" data-onstyle="success" class="toggle" id="toggle-one">  
<input type="checkbox" checked data-toggle="toggle" data-onstyle="success" class="toggle" id="toggle-two">
<input type="checkbox" checked data-toggle="toggle" data-onstyle="success" class="toggle" id="toggle-three">

$('#toggle-one').bootstrapToggle('on');
$('#toggle-two').bootstrapToggle('off');
$('#toggle-three').bootstrapToggle('off');

Answers 1

  • You want your toggle buttons to behave more like radio rather than checkbox, so why not just convert them all to radio?

    <input type="radio" data-toggle="toggle" data-onstyle="success"
        class="toggle mytoggle" id="toggle-one">
    

    As for the jQuery part, here's something that works (an alternative if $('.toggle').bootstrapToggle('off') fails):

    $('.toggle').click(function(){
      $(this).find('input.toggle').removeClass('off');
    
      $('.toggle').not(this).each(function(){
        $(this).addClass('off');
        $(this).removeClass('btn-success');
      }); /*END each*/
    
      $(this).removeClass('off');
      $(this).addClass('btn-success');
    }) /*END click*/
    

    JSFiddle demo here.


Related Articles