bootstrap switch setState using a jquery function

pablinho picture pablinho · Dec 5, 2015 · Viewed 27.3k times · Source

I'm trying to set the state of a bootstrap switch with two external buttons, this is the code:

    <div>
        <input type="checkbox" name="switch" id="switch" value="1" data-on-text="ON" data-off-text="OFF" />
    </div>

    <div>
        <a id="set_on">ON</a>
        <a id="set_off">OFF</a>
    </div>

<script src="assets/jquery.min.js" type="text/javascript"></script>
<script src="assets/jquery-ui.min.js" type="text/javascript"></script>
<script src="assets/bootstrap.min.js" type="text/javascript"></script>
<script src="assets/bootstrap-switch.js"></script>
<script>
    $("#switch").bootstrapSwitch();
    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('setState', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('setState', false);
    });
</script>

Clicking on the buttons ON or OFF the switch no not toggle its state. Looking on the console of the browser I read this error: TypeError: $(...).bootstrapSwitch is not a function

If I try to set the State of the bootstrap switch outside the function in this way:

<script>
    $("#switch").bootstrapSwitch();
    $("#switch").bootstrapSwitch('setState', false);
</script>

the switch toggle correctly to the ON state.

Answer

Amit Chaudhari picture Amit Chaudhari · Dec 5, 2015

Please replace your code with below :

    <script type="text/javascript">
    $( document ).ready(function() {
    $("#switch").bootstrapSwitch();

    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('state', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('state', false);
    });
    });
    </script>