2014-03-03 123 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