necroface
necroface

Reputation: 3465

Bootstrap Toggle - One is on, the other is off

I'm using this library to implement toggle buttons. I have two toggle buttons. My purpose is when switching on one of them, the other should be switched off.

As the library instructs, I create two input elements:

<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-on" checked value="true">
<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-off">

And my jQuery code to handle them:

$('.switch-on').change(function(){
    $(this).removeClass('switch-on');
    $(this).addClass('switch-off');
    $(this).bootstrapToggle();
});

$('.switch-off').click(function(){
    $(this).removeClass('switch-off');
    $(this).bootstrapToggle();
    $('.switch-on').click();
    $(this).addClass('switch-on');
});

I have tried many ways, including changing class names, triggering events, but totally in vain. The class names are not even changed when I inspect elements. Why isn't it working?

Upvotes: 0

Views: 5497

Answers (1)

Rahul
Rahul

Reputation: 18557

Try this snippet,

$("#toggle1").change(function() {
  if ($(this).is(":checked")) {
      $("#toggle2").bootstrapToggle('off');
  }
});
$("#toggle2").change(function() {
  if ($(this).is(":checked")) {
      $("#toggle1").bootstrapToggle('off');
  }
});
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-on toggle" checked value="true" id="toggle1">
<input type="checkbox" data-toggle="toggle" data-style="ios" data-size="normal" data-on="&#8203;" data-off="&#8203;" class="switch switch-off toggle" id="toggle2">

Upvotes: 6

Related Questions