javascript 检查复选框是否被选中(js/jquery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10253512/
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
Check if a check box is checked or not (js/jquery)
提问by Baruch
I want to check if a certain check box is selected using JavaScript/jQuery.
我想检查是否使用 JavaScript/jQuery 选中了某个复选框。
Here is the code I tried:
这是我试过的代码:
var a;
if ($("#add_desc").checked == 1){
a = "true";
}else{
a= "false";
}
I have also tried:
我也试过:
var a;
if ($("#add_desc").checked){
a= "true";
}else{
a= "false";
}
It always returns false once I alert the variable a
.
一旦我提醒变量,它总是返回 false a
。
Any idea why it won't work for me? Am I doing it wrong?
知道为什么它对我不起作用吗?我做错了吗?
Thanks!
谢谢!
回答by Kevin B
To get the value of the checked
property on a checkbox input, use the .prop()
method, or get the value directly from the DOM element. [0]
returns the first selected DOM element.
要获取checked
复选框输入上的属性值,请使用该.prop()
方法,或直接从 DOM 元素获取值。[0]
返回第一个选定的 DOM 元素。
var a;
if ($("#add_desc")[0].checked){
a= "true";
}else{
a= "false";
}
or
或者
var a;
if ($("#add_desc").prop("checked")){
a= "true";
}else{
a= "false";
}
Edit
For versions of jQuery older than 1.6, .prop
didn't exist, use .attr
as a direct replacement.
编辑
对于早于 1.6 的 jQuery 版本,.prop
不存在,.attr
用作直接替换。
回答by Robin Maben
Simple,
简单的,
var a = $('#element:checkbox').is(':checked');
回答by Nathan
The "jQuery way" would be to use .is(":checked")
:
“jQuery 方式”将使用.is(":checked")
:
var a;
if ($("#add_desc").is(":checked")){ // box is checked
a = "true";
} else{ // box is not checked
a= "false";
}
I use this a lot in my web apps and it works perfectly.
我在我的网络应用程序中经常使用它,它运行良好。
From the jQuery .is
documentation page:
Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification. This is often useful inside callbacks, such as event handlers.
与其他过滤方法不同,.is() 不会创建新的 jQuery 对象。相反,它允许您无需修改即可测试 jQuery 对象的内容。这在回调中通常很有用,例如事件处理程序。
回答by Michael Berkompas
回答by newtron
try:
尝试:
if ($('#add_desc').is(':checked')) {
a = "true";
} else {
b = "false";
}
you may also not want to use strings, i.e. use true
and false
instead of "true"
and "false"
您可能也不想使用字符串,即使用true
andfalse
而不是"true"
and"false"
回答by Shehzad
Try
尝试
$get("#add_desc").checked == true
Also
还
$("#add_desc").prop("checked", true);
$("#add_desc").prop("checked", false);