Reputation: 2505
I have a table that has five checkboxes(Add, Edit, View, Delete, All). These table rows are generated dynamically. Code for that is as follows:
<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>
I am trying to work around my last checkbox(All). My requirement is that when I check that "All" checkbox, the remaining checkboxes should be checked and when I uncheck "All" checkbox, the remaining checkboxes should be unchecked.
I am using following Jquery for this.
<script>
$('.CheckAll').on('change', function () {
$(this).closest('.grouprow').find(':checkbox').not(this).prop('checked', this.checked);
});
$('table tr input:checkbox:not(".CheckAll")').on('change', function () {
if (!this.checked) {
$('.CheckAll').prop('checked', false);
}
//var checkedBoxes = $(this).closest('.grouprow').find('input:checkbox:not(".CheckAll"):checked');
//if (checkedBoxes.length == 4) {
// $('.CheckAll').prop('checked', true);
//}
});
</script>
Everything works fine, but when I uncheck any one of the checkbox in any row when all the remaining rows checkboxes are checked, the "All" checkbox for all the rows is unchecked. Any help?
Upvotes: 0
Views: 870
Reputation: 25527
change the code like this
$(document).ready(function () {
$('.CheckAll').on('change', function () {
$(this).parent().parent().find('input[type=checkbox]').prop('checked', this.checked);
});
$('table tr input:checkbox:not(".CheckAll")').on('change', function () {
if (!this.checked) {
$(this).parent().parent().find('.CheckAll').prop('checked', false);
}
});
});
Because you are unchecking all the chackboxes that have the class "CheckAll". This code will uncheck only the closest checkbox.
updated fiddle
Upvotes: 2
Reputation: 74738
I think you should check for the length:
if ($('.grouprow').find(':checked').length != $('.grouprow').find(':checkbox').length) {
$('.CheckAll').prop('checked', false);
}
Upvotes: 0