jQuery 复选框值总是返回“on”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16611704/
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
Checkbox value always returns "on"?
提问by Maxim Kumpan
I'm trying to return the value of a checkbox to enable and disable a button. Making the checkbox is not a problem, the problem is the check box value always returns on. How should I get a value indicating if the checkbox is checked?
我正在尝试返回复选框的值以启用和禁用按钮。制作复选框不是问题,问题是复选框值总是返回。我应该如何获得指示复选框是否被选中的值?
HTML:
HTML:
<form>
<input type="checkbox" id="checkbox" /> <label>Do you agree </label><br />
<input type="button" value="Continue" id="button" disabled="disabled" />
</form>
Javascript:
Javascript:
$('#checkbox').change(function(){
var checkboxValue = $(this).val();
alert(checkboxValue);
});
回答by Maxim Kumpan
回答by gdoron is supporting Monica
It seems that you need checked
看来你需要 checked
var checkboxValue = this.checked;
回答by Shardayyy
A couple of things is going on here
这里发生了一些事情
- the check box as is does not have a value
- you should be checking to see if its checked or not
- 复选框原样没有值
- 你应该检查它是否被检查
try this
尝试这个
$('#checkBox').prop('checked');
if its checked you should get back true and false if its not checked.
如果它被选中,你应该返回 true 和 false 如果它没有被选中。
回答by RemarkLima
Trying using (If you're using jQuery 1.6+):
尝试使用(如果您使用的是 jQuery 1.6+):
var checkboxValue = $(this).prop('checked');
This should return a true
or false
correctly.
这应该正确返回 atrue
或false
。
回答by Petr Vostrel
Or what about making use of the :checked
Selector?
或者如何使用:checked
Selector?
$(this).is(':checked') // returns true if checked and false otherwise
回答by Rick
Try using is(':checked')instead of .val
尝试使用is(':checked')而不是.val
$('#checkbox').change(function(){
var checkboxValue = $(this).is(':checked');
alert(checkboxValue);
});
It returns true or false
它返回真或假
See also jQuery val() and checkboxes
另请参阅 jQuery val() 和复选框
回答by Cannicide
Here is a code to do this, no jquery, based off of @gdoron's answer.
这是基于@gdoron 的答案的代码来执行此操作,没有 jquery。
document.getElementById("checkbox").addEventListener("change", function() {
if (this.checked) {
//Whatever u want to do if checked
}
else {
//Whatever u want to do if not checked
}
})
Try checking/unchecking the checkbox in the below snippet to see this in action...
尝试选中/取消选中以下代码段中的复选框以查看此操作...
document.getElementById("checkbox").addEventListener("change", function() {
if (this.checked) {
//Whatever u want to do if checked
alert("u check");
}
else {
//Whatever u want to do if not checked
alert("u uncheck");
}
})
<input type="checkbox" id="checkbox" />Coconuts?