how to change a bootstrap switch from OFF state to ON state using javascript.
the switch html code is below,
<input type="checkbox" class="alert-status" name="ab1" id="ab1" data-size="normal" data-on-text="OFF" data-off-text="ON" checked data-bootstrap-switch data-off-color="success" data-on-color="danger">
script code,
$('.alert-status').bootstrapSwitch('state', false);
i tried some steps way but did not get it
3
Answers
Well, it’s just ‘a checkbox’, so have you tried (to turn it ON):
$('#ab1').prop('checked', true);
Use
false
to turn it off.Edit: Yes this works. Go to the Bootstrap docs: https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches
And write in the console of your browser:
document.getElementById('flexSwitchCheckDefault').checked = true;
And notice the "Default switch checkbox input" is turned on.
You need to get the checkbox by id and then set the
checked
property to true or false:document.getElementById('ab1').checked = true;
– for ON statedocument.getElementById('ab1').checked = false;
– for OFF stateFor the sake of good practice let’s just wrap them into functions: