简体   繁体   中英

how to change a bootstrap switch from ON state to OFF state using javascript

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

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 state

document.getElementById('ab1').checked = false; - for OFF state

For the sake of good practice let's just wrap them into functions:

function setToOn(){
  document.getElementById('ab1').checked = true;
}

function setToOff(){
  document.getElementById('ab1').checked = false;
}

 $('.switch').bootstrapSwitch('state'); $('.switch').on('switchChange.bootstrapSwitch', function() { var check = $('.bootstrap-switch-on'); switch (check.length) { case 0: console.log('OFF', check.length) break; case 1: console.log('ON', check.length) break; default: // code block } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/css/bootstrap2/bootstrap-switch.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.min.js"></script> <input type="checkbox" class="switch" data-on-color="primary" data-off-color="primary" value="true">

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