Home > Software design >  how to change a bootstrap switch from ON state to OFF state using javascript
how to change a bootstrap switch from ON state to OFF state using javascript

Time:01-27

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

the switch html code is below,

<input type="checkbox" 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

CodePudding user response:

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.

CodePudding user response:

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;
}

CodePudding user response:

$('.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"  data-on-color="primary" data-off-color="primary" value="true">

  • Related