小编典典

检查是否已使用jQuery选中复选框

html

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

我正在使用以下代码,但是无论ID为何,它始终返回已选中复选框的数量。

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

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

阅读 334

收藏
2020-05-14

共2个答案

小编典典

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;
2020-05-14
小编典典

$('#' + id).is(":checked")

如果选中此复选框,则可以得到。

对于具有相同名称的复选框数组,您可以通过以下方式获取已选中复选框的列表:

var $boxes = $('input[name=thename]:checked');

然后遍历它们并查看已检查的内容,您可以执行以下操作:

$boxes.each(function(){
    // Do stuff here with this
});

要查找已检查的数量,您可以执行以下操作:

$boxes.length;
2020-05-14