检查复选框是否被 jQuery 选中 [英] Check if checkbox is checked with jQuery

查看:26
本文介绍了检查复选框是否被 jQuery 选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用复选框数组的 id 来检查复选框数组中的复选框是否被选中?

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

我正在使用以下代码,但无论 id 为何,它始终返回选中复选框的计数.

I am using the following code, but it always returns the count of checked checkboxes regardless of id.

function isCheckedById(id) {
    alert(id);
    var checked = $("input[@id=" + id + "]:checked").length;
    alert(checked);

    if (checked == 0) {
        return false;
    } else {
        return true;
    }
}

推荐答案

ID 在您的文档中必须是唯一的,这意味着您不应该这样做:

IDs must be unique in your document, meaning that you shouldn't do this:

<input type="checkbox" name="chk[]" id="chk[]" value="Apples" />
<input type="checkbox" name="chk[]" id="chk[]" value="Bananas" />

相反,删除 ID,然后按名称或包含元素选择它们:

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id="checkArray">
    <input type="checkbox" name="chk[]" value="Apples" />

    <input type="checkbox" name="chk[]" value="Bananas" />
</fieldset>

现在是 jQuery:

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
//there should be no space between identifier and selector

// or, without the container:

var atLeastOneIsChecked = $('input[name="chk[]"]:checked').length > 0;

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

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