Bootstrap data-toggle="toggle" 已选中,jquery 未选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37983481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bootstrap data-toggle="toggle" checked,unchecked by jquery
提问by Udara
I'm using bootstrap checkbox with data-toggle="toggle" attribute. I want to set it checked and unchecked with jquery. I tried many ways but it didn't work. Here is my code.
我正在使用带有 data-toggle="toggle" 属性的引导程序复选框。我想用jquery将它设置为选中和取消选中。我尝试了很多方法,但没有奏效。这是我的代码。
<input type="checkbox" data-toggle="toggle" data-size="small" id="checkbox1">
for button click:
对于按钮点击:
$("#checkbox").attr('checked',true);
But it's working when I remove data-toggle="toggle"
attribute.
但是当我删除data-toggle="toggle"
属性时它正在工作。
Any help is greatly appreciated!
任何帮助是极大的赞赏!
Thanks.
谢谢。
回答by Shaunak D
From the documentation,
从文档中,
Use
用
$('#checkbox1').bootstrapToggle('on')
If you are using prop()
or attr()
, there is a workaround,
如果您正在使用prop()
或attr()
,则有一种解决方法,
$('#checkbox1').prop('checked', true).change()
回答by Mani
It is working if you use id name is correct see the example below
如果您使用的 id 名称正确,它就可以工作,请参见下面的示例
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<input type="checkbox" data-toggle="toggle" data-size="small" id="checkbox1">Test
</div>
<script>
$(document).ready(function(){
$("#checkbox1").attr('checked',true);
});
</script>
</body>
</html>