twitter-bootstrap 引导开关检查检查状态总是返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24915511/
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-10-21 21:10:36  来源:igfitidea点击:

bootstrap switch checking checked status always returns false

javascriptjquerytwitter-bootstrapbootstrap-switch

提问by ldeluca

I don't want to listen for the event of the switch being toggled, instead I want to use JavaScript to check it's current checked state.

我不想监听开关被切换的事件,而是想使用 JavaScript 来检查它的当前选中状态。

<input type="checkbox" name="pushtoggle" state="true" data-role="none">

I have this simple JavaScript to check the checked value:

我有这个简单的 JavaScript 来检查选中的值:

if ($('#pushtoggle').is(':checked')){ alert('checked'); } else { alert('not checked');}

No matter which state (on or off) the switch is set to I always get the alert that it is not checked.

无论开关设置为哪种状态(开或关),我总是收到未检查的警报。

I initialized the toggle switch using:

我使用以下方法初始化了拨动开关:

$("[name='pushtoggle']").bootstrapSwitch();

I also tried setting the checked attribute within the input tag. Nothing works to get me the correct state of the switch.

我还尝试在输入标签中设置选中的属性。没有什么能让我获得正确的开关状态。

回答by Claudio Redi

You don't have any element with id = pushtogglebut you're using an id selector.

您没有任何带有 id = 的元素,pushtoggle但您使用的是 id 选择器。

Try with this

试试这个

if ($('[name="pushtoggle"]').is(':checked')){ 
  alert('checked'); 
} 
else { 
  alert('not checked');
}

回答by Dunia Taymi Machado

$("[name='pushtoggle']").bootstrapSwitch('state')