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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:09:18  来源:igfitidea点击:

Bootstrap data-toggle="toggle" checked,unchecked by jquery

jquerytwitter-bootstrapcheckbox

提问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>

回答by TechnicalKalsa

You can use this code.

您可以使用此代码。

Jquery Code

查询代码

$('#chk').prop('checked',true);

HTML Code

HTML代码

<input type="checkbox" id="chk">

Live Demo

现场演示