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.
Examples of Bootstrap switch use: A switch has the markup of a custom checkbox but uses the .custom-switch class to render a toggle switch. Switches also support the disabled attribute.
Bootstrap switch / Bootstrap toggle Bootstrap switch/toggle is a simple component used for activating one of two predefined options. Commonly used as an on/off button. It's mostly used in a number of various forms since they are very simple to use and cut the time one needs to fill all the inputs.
You can read the state by reading checkbox state: // switch to OFF $ ('.bootstrap-switch-container input').prop ('checked') // false // switch to ON $ ('.bootstrap-switch-container input').prop ('checked') // true Ah, okay. Thanks so much.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With