[英]How to check if check box is checked in this example (javascript/jQuery.)
I need to check if a checkbox is checked or not in order to display an error message. 我需要检查是否选中了一个复选框才能显示错误消息。 So far I thought that this should work (if not checked than it should be empty I thought).
到目前为止,我认为这应该可行(如果未选中,我认为应该为空)。
CODE 码
<span id="sc_info" style="float: right; padding-right: 5px;">
<input type="checkbox" name="terms" id="sc_terms" value="" checked="checked" />
<br /><label class="error" for="body" id="terms_error">This field is required.</label>
</form>
<script>
$(document).ready(function() {
//Story Form
$('.error').hide();
$(".button").click(function() {
$('.error').hide();
var terms = $("input#sc_terms").val();
if (terms == "") { //if is not checked
$("label#terms_error").show(); //show error message
$("input#sc_terms").focus(); //focus on an empty element
return false;
}
});
});
</script>
But this code doesn't work. 但是此代码不起作用。 can anyone suggest how to check if checkbox is checked?
有人可以建议如何检查复选框是否被选中吗?
Use jQuery's :checked
selector: 使用jQuery的
:checked
选择器:
if ($('#sc_terms').is(':checked')) {
// Checkbox is checked, do stuff
}
else {
// Checkbox is not checked, do stuff
$("label#terms_error").show(); //show error message
$("input#sc_terms").focus();
}
If you simply want to see if it's not checked: 如果您只是想查看是否未选中:
if ($('#sc_terms:not(:checked)')) {
// Checkbox is checked, do stuff
$("label#terms_error").show(); //show error message
$("input#sc_terms").focus();
}
Note: Since you're using the ID selector, prefacing your selector with input
or label
is not necessary. 注意:由于您使用的是ID选择器,因此不需要在选择器前添加
input
或label
。
Something like: 就像是:
if( $("input#sc_terms").is(":checked") )
// is checked
And not checked: 而不检查:
if( $("input#sc_terms").is(":not(:checked)") )
// not checked
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.