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

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

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

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

当前回答

用于检查和设置复选框的简单演示。

jsfiddle!

$('.attr-value-name').click(function() {
    if($(this).parent().find('input[type="checkbox"]').is(':checked'))
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', false);
    }
    else
    {
        $(this).parent().find('input[type="checkbox"]').prop('checked', true);
    }
});

其他回答

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;
$('#' + id).is(":checked")

如果选中该复选框,则会出现这种情况。

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

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

然后,要循环浏览它们并查看检查内容,您可以执行以下操作:

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

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

$boxes.length;

这也是我经常使用的一个想法:

var active = $('#modal-check-visible').prop("checked") ? 1 : 0 ;

如果勾选,则返回1;否则将返回0。

对于带有id的复选框

<input id="id_input_checkbox13" type="checkbox"></input>

你可以简单地

$("#id_input_checkbox13").prop('checked')

您将获得true或false作为上述语法的返回值。您可以在if子句中将其用作普通布尔表达式。

您的问题并不清楚:您希望在输入时给出“checkbox array id”,在输出时得到true/false,这样您就不知道选中了哪个复选框(正如您的函数名所示)。下面是我对isCheckedById主体的建议,它在输入时接受复选框id,在输出时返回true/false(这很简单,但您的id不应该是关键字),

this[id].checked

函数isCheckedById(id){返回此[id].checked;}//测试函数检查(){console.clear()console.log('1',isCheckedById(“myCheckbox1”));console.log('2',isCheckedById(“myCheckbox2”));console.log('3',isCheckedById(“myCheckbox3”));}<label><input id=“myCheckbox1”type=“checkbox”>check 1</label><label><input id=“myCheckbox2”type=“checkbox”>check 2</label><label><input id=“myCheckbox3”type=“checkbox”>check 3</label><!-- 输入周围的标签使文本可单击--><br><button onclick=“check()”>show checked</button>