Binding onclick event to bootstrap-switch

Zengetsu picture Zengetsu · Nov 2, 2016 · Viewed 8.3k times · Source

I'm building a form that's supposed to hide and show content according to bootstrap-switch selections made by the user. The onclick="documentFilter event works on normal check-boxes; however, the moment I initialise bootstrap-switch, the code does not work as intended. Any idea what I'm missing? Thanks!

Answer

Rory McCrossan picture Rory McCrossan · Nov 2, 2016

If you check the documentation of the Bootstrap Switch library you'll see it has a onSwitchChange property which you can provide a function to. This function is executed when the switch is toggled. This has the added benefit of removing the need for the outdated and ugly on* event attribute. Try this:

$("[name='my-checkbox']").bootstrapSwitch({
  onSwitchChange: function(e, state) {
    $('#hideableDiv').toggle(state);
  }
});
.hiddenByDefault { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap-theme.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap2/bootstrap-switch.min.css" />

<div class="container">
  <label>
    <input type="checkbox" name="my-checkbox" onclick="documentFilter(this, '#hideableDiv')">Some caption
  </label>

  <div id="hideableDiv" class="hiddenByDefault">Some hidable content
  </div>
</div>