小编典典

检查是否使用 jQuery 检查了复选框

all

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

我正在使用以下代码,但它总是返回选中复选框的计数,而不管 id 是什么。

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

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

阅读 85

收藏
2022-02-25

共1个答案

小编典典

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

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

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

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

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

现在是 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;
2022-02-25