【问题标题】:How to check a checkbox when all the checkboxes below it are checked?当下面的所有复选框都被选中时,如何选中一个复选框?
【发布时间】:2015-12-20 21:53:34
【问题描述】:

我正在以这种方式将 tr 和 td 动态添加到表中。

var arr=[1,2,3];

                var trtest = "<tr>";
                trtest = trtest +"<tr><td><input type='checkbox' onclick=onAllCheckBoxClick('" + arr+ "') class = 'all' id ='all'>All</td></tr>";

$.each(arr, function(i, tmp) {
                    trtest = trtest +"<tr><td><input type='checkbox' onclick=onCheckBoxClick('" + this+ "','" + arr+ "') class = 'all' id ='"+tmp+"'/>"+tmp+"</td></tr>";
                });

此代码正在运行,我通过这种方式获得了 4 个复选框,

All
    1

    2

    3

在这里,当我尝试检查单个子复选框的 1、2、3 时,必须选中所有复选框。

我尝试以这种方式将此点击事件添加到每个复选框,

function onCheckBoxClick(checkBoxId,arr){
        var chkselected = [];
            $('#generateTable').find(':checkbox:checked').each(function() {
                chkselected.push(this.id);
            });
            //
            if (arr.split(",").length == chkselected.length && ($('#'+checkBoxId).is(':checked') == true)) {
                $('#all').attr('checked',true);
            }
            //
            else if (arr.split(",").length == chkselected.length && ($('#'+checkBoxId).is(':checked') == false)) { 
                $('#all').attr('checked',false);                
            }
}

问题是当我检查 1,2,最后是 3 立即检查所有复选框,

但是当我最后尝试检查 3,2 和 1 时,未选中所有复选框。

如果选中 1,2,3,我希望全部选中,如果未选中 1,2,3 中的任何一个,我希望全部取消选中。

我是 jQuery 新手,谁能帮我解决这个问题?

【问题讨论】:

  • 请在jsFiddle上发布一个说明您的问题的功能示例。

标签: javascript jquery html checkbox html-table


【解决方案1】:

为“组”中的所有复选框分配相同的名称,类似于处理无线电输入的方式。

然后为全选复选框分配相同的名称并分配某种独特的项目,以便您可以捕获该单个项目的点击事件(在我的示例中,我使用了 role="selectall" 您可以使用任何您想要的) .

<input type="checkbox" id="checkAll" name="chkGroup1" role="selectall" />
<label for='checkAll'>Select All</label>
<br />
<input type='checkbox' id='checkbox1' name='chkGroup1' />
<label for='checkbox1'>product1</label>
<br />
<input type='checkbox' id='checkbox2' name='chkGroup1' />
<label for='checkbox2'>product2</label>
<br />
<input type='checkbox' id='checkbox3' name='chkGroup1' />
<label for='checkbox3'>product3</label>
<br />
<input type='checkbox' id='checkbox4' name='chkGroup1' />
<label for='checkbox4'>product4</label>

由于您已经分配了名称,您可以将其用作您的 jQuery 选择器,并且您正在将输入的选中属性分配给具有相同名称的项目的测试。

$('input:checkbox[role=selectall]').click(function () {

    $('[name="' + this.name + '"]').prop('checked', this.checked)

})

http://jsfiddle.net/SeanWessell/11h0f2jm/

【讨论】:

  • 我想反其道而行之。如果 checkbox1,checkbox2,checkbox3,checkbox4 被选中,那么自动 checkAll 必须被选中。
  • 如果 chkGroup1 中的所有复选框都被选中,则自动选择 checkAll
  • atleaset 如果 chkGroup1 中的任何复选框未选中,则自动 checkAll 必须取消选中。
  • 像这样,您需要从全选按钮中删除 name="group" 吗? jsfiddle.net/SeanWessell/rLxdpp4v
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 2023-04-02
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多