2013-08-29 56 views
0

我有一個表有兩種類型的行(主行和子行)。 主行的行ID是「mainRow」+ prId(tr的屬性)。 子行的行號是「subRow」+ prId(tr的屬性)+ rowNo。如果所有的sbu複選框爲真,設置主複選框爲真

我必須做的是,如果所有子行的複選框都被選中,那麼主行的複選框必須被選中。有人可以幫我嗎。

<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> 
+0

我通過使用tbody元素將每個組列在一個單獨的表部分啓動。然後在每個tbody或表上放置一個點擊監聽器。如果它從複選框中獲得點擊,它會查看相關表格部分中的輸入,並且如果檢查了所有子目錄,則檢查該集合的主複選框。否則,它將取消選中主複選框。如果用戶選中主複選框,則可能需要檢查所有子複選框。 – RobG

回答

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.