如果所有sbu复选框都为true,则将main复选框设置为true

时间:2013-08-29 04:34:02

标签: javascript

我有一个包含两种行(主行和子行)的表。 主行的行ID是“mainRow”+ prId(tr的属性)。 子行的行id是“subRow”+ prId(tr的属性)+ rowNo。

我要做的是,如果选中子行的所有复选框,则必须选中主行的复选框。有人可以帮助我。

<tr id="mainRow2" prId = "2"><td><input type="checkbox" id="main0" ></td></tr>
    <tr id="subRow2_1" prId = "2"><td><input type="checkbox" id="subRow2_1_1" ></td></tr>
    <tr id="subRow2_2" prId = "2"><td><input type="checkbox" id="subRow2_2_1" ></td></tr>
    <tr id="subRow2_3" prId = "2"><td><input type="checkbox" id="subRow2_3_1" ></td></tr>

<tr id="mainRow5" prId = "5"><td><input type="checkbox" id="main1" ></td></tr>
    <tr id="subRow5_1" prId = "5"><td><input type="checkbox" id="subRow5_1_1" ></td></tr>
    <tr id="subRow5_2" prId = "5"><td><input type="checkbox" id="subRow5_2_1" ></td></tr>
    <tr id="subRow5_3" prId = "5"><td><input type="checkbox" id="subRow5_3_1" ></td></tr>
    <tr id="subRow5_4" prId = "5"><td><input type="checkbox" id="subRow5_4_1" ></td></tr>

1 个答案:

答案 0 :(得分:0)

将以下jQuery代码添加到您的页面(确保在页面上包含jQuery脚本)。

虽然您的复选框组织错误,但您应该重新组织表格。

$('input').change(function() {

  $("tr[id^='mainRow']").each(function(i,v){
    var id = $(v).attr('id');
    id = id.split('mainRow')[1];
    var subs = $("input[id^='subRow"+id+"']");
    var checkedSubs = $("input[id^='subRow"+id+"']:checked");
    console.log(checkedSubs.length);

    if(subs.length == checkedSubs.length)
      $('input',v).attr('checked',true);
    else
      $('input',v).attr('checked',false);
  });

});

Live example here.

相关问题