2014-03-03 124 views
1

我有一個表,我填充一些數據,除了每個複選框,最後一個複選框是「全部」。 當我檢查這個「ALL」複選框時,應該選中複選框,反之亦然。如何做選擇所有當選中一個複選框

填充數據的代碼。

<div class="tablecontatiner"> 

<table> 
       <tr> 
        <th>Function</th> 
        <th>Add</th> 
        <th>Edit</th> 
        <th>View</th> 
        <th>Delete</th> 
        <th>All</th> 
        </tr> 
       @foreach (var item in Model) 
       { 
       <tr class="grouprow"> 
        <td><input type="hidden"/><input id="@(item.Func_Code)" type="checkbox" style="visibility:hidden" />@item.FunctionName</td> 
        <td><input id="@(item.Func_Code + "A")" type="checkbox" value="Add" @(item.Add==true?"checked":"") /></td> 
        <td><input id="@(item.Func_Code + "E")" type="checkbox" value="Edit" @(item.Edit==true?"checked":"") /></td> 
        <td><input id="@(item.Func_Code + "V")" type="checkbox" value="View" @(item.View==true?"checked":"")/></td> 
        <td><input id="@(item.Func_Code + "D")" type="checkbox" value="Delete" @(item.Delete==true?"checked":"")/></td> 
        <td><input id="@(item.Func_Code + "ALL")" type="checkbox" value="All"/></td> 
        </tr> 
       } 
</table> 
</div> 

和我的UI看起來像this

回答

2

試試這個

$('#checkboxAll').on('change', function() { 
    $(this).closest('.grouprow').find(':checkbox').not(this).prop('checked', this.checked); 
}); 
$('table tr input:checkbox:not("#checkboxAll")').on('change', function() { 
    if (!this.checked) { 
     $('#checkboxAll').prop('checked', false); 
    } 
}); 

DEMO

+0

什麼是#chekcboxAll她...該複選框的ID?或值或複選框? – Santosh

+0

應該檢查/取消選中全部的複選框的ID – Anton

+0

嘗試了您的演示...但沒有爲我取消選中任何一個checkbox.the所有複選框應該取消選中 – Santosh

1

嘗試

jQuery(function ($) { 
    //listen to the change of checkbox in the last td 
    $('.tablecontatiner td:last-child input').on('change', function() { 
     //update the checked property of all checkboxes in the same row as the changed checkbox 
     $(this).closest('tr').find('input[type="checkbox"]').not(this).prop('checked', this.checked); 
    }) 
}) 
0

嘗試,

$('#chkAll')。on('click',function(){(this).closest('。grouprow')。find(':checkbox')。not(this).prop ('checked',this.checked); });

0

安東的解決方案非常優雅。 如果加載(或重新加載)表,不希望在每次重新加載時設置事件處理程序,然後我就改了一下解決方法:

$('.tablecontatiner').on('change', '[id$=All]', function() { 
    $(this).closest('.grouprow').find('input').not(this).prop('checked', this.checked); 
}); 

備註:另外我想放棄「checkboxAll」 級到每個 「ALL」 複選框,因此它看起來像:

<input id="@(item.Func_Code + "ALL")" type="checkbox" value="All" class="checkboxAll"/> 

,然後上面的代碼將是:

$('.tablecontatiner').on('change', '.checkboxAll', function() { 
    $(this).closest('.grouprow').find('input').not(this).prop('checked', this.checked); 
}); 

http://jsbin.com/jetewayi/1/edit

+0

未勾選複選框時如何?當時應該取消選中「全部」複選框 – Santosh

+0

當然,如果您改變它,它會因爲您改變而改變。所以你不應該用「全部」複選框做更多的事情。這就是爲什麼不應用(this)過濾器。試試我添加到我的答案中的jsbin示例。 – Alexander