Search code examples
jquerybootstrap-switch

Binding onclick event to bootstrap-switch


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!

<!--DEPENDENCIES-->
<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>

<!--HTML-->
<body>
    
    <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>

</body>

<!--PAGE-SPECIFIC SCRIPT-->

<script type="text/javascript">

//Initialise BootstrapSwitch
$("[name='my-checkbox']").bootstrapSwitch();

//Unchecked on load
$(".hiddenByDefault").hide();

//document filter function
function documentFilter(trigger, target) {
    var $target = $(target);

    $(trigger).change(function () {
        $target.toggle(this.checked);
    });
}

</script>


Solution

  • If you check the source 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>