简体   繁体   中英

bootstrap switch setState using a jquery function

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.

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>

Try wrapping your code inside $( document ).ready(function() {}); so that all of your DOM elements loads before jQuery code is executed like this :

<script>
$( document ).ready(function() {
    $("#switch").bootstrapSwitch();
    $("#switch").bootstrapSwitch('setState', false);
});
</script>

try using it in your full script like this -

<script>

 $( document ).ready(function() {
    $("#switch").bootstrapSwitch();
    $( "#set_on" ).click(function() {
        $("#switch").bootstrapSwitch('setState', true);
    });
    $( "#set_off" ).click(function() {
        $("#switch").bootstrapSwitch('setState', false);
    });
});

</script>

你可以尝试使用bootstrapSwitch() ,像这样

 $("[name = 'status']").bootstrapSwitch();
 <input name = "status" type="checkbox">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM