如何检查在此示例中是否选中了复选框(javascript / jQuery。)

我需要检查是否选中了复选框才能显示错误消息。 到目前为止,我认为这应该工作(如果不检查,它应该是空的,我想)。

  
$(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; } }); });

但是这段代码不起作用。 任何人都可以建议如何检查复选框是否被选中?

使用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选择器,因此无需使用inputlabel为选择器添加前缀。

就像是:

 if( $("input#sc_terms").is(":checked") ) // is checked 

而不是检查:

 if( $("input#sc_terms").is(":not(:checked)") ) // not checked