【问题标题】:How to check if check box is checked in this example (javascript/jQuery.)如何检查此示例中是否选中了复选框(javascript/jQuery。)
【发布时间】:2012-01-13 12:48:56
【问题描述】:

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

代码

<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>

但是这段代码不起作用。谁能建议如何检查复选框是否被选中?

【问题讨论】:

    标签: javascript jquery html checkbox


    【解决方案1】:

    类似:

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

    未检查:

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

    【讨论】:

    • .not.filter的反面,返回一个jQuery对象,它总是通过if子句。
    • 由于某种原因,它在两种情况下仍然显示错误消息,当它被检查时,当它没有被检查时...... if( $("input#sc_terms").not(":checked") ) { $("label#terms_error").show();
    【解决方案2】:

    使用 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

    【讨论】:

      猜你喜欢
      • 2010-10-28
      相关资源
      最近更新 更多