[英]How to check if check box is checked in this example (javascript/jQuery.)
我需要检查是否选中了一个复选框才能显示错误消息。 到目前为止,我认为这应该可行(如果未选中,我认为应该为空)。
码
<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>
但是此代码不起作用。 有人可以建议如何检查复选框是否被选中吗?
使用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 ($('#sc_terms:not(:checked)')) {
// Checkbox is checked, do stuff
$("label#terms_error").show(); //show error message
$("input#sc_terms").focus();
}
注意:由于您使用的是ID选择器,因此不需要在选择器前添加input
或label
。
就像是:
if( $("input#sc_terms").is(":checked") )
// is checked
而不检查:
if( $("input#sc_terms").is(":not(:checked)") )
// not checked
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.