简体   繁体   English

如何使用 javascript 将引导开关从 ON state 更改为 OFF state

[英]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.如何使用 javascript 将引导开关从 OFF state 更改为 ON state。

the switch html code is below,开关 html 代码如下,

<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);好吧,它只是一个“复选框”,所以您是否尝试过(将其打开): $('#ab1').prop('checked', true); Use false to turn it off.使用false将其关闭。

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; Go 到 Bootstrap 文档:https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches并在浏览器的控制台中写入: 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:您需要通过 id 获取复选框,然后将checked属性设置为 true 或 false:

document.getElementById('ab1').checked = true; - for ON state - ON state

document.getElementById('ab1').checked = false; - for OFF state - 关闭 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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