如何检查此示例中是否选中复选框(javascript / jQuery。) [英] How to check if check box is checked in this example (javascript/jQuery.)

查看:133
本文介绍了如何检查此示例中是否选中复选框(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

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?

推荐答案

使用jQuery的 :checked 选择器:

Use jQuery's :checked selector:

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.

这篇关于如何检查此示例中是否选中复选框(javascript / jQuery。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆