Reputation: 51
I have a scenario where I am populating a datatable with n number of rows. The rows are populated in groups with a particular group id. Say, if there are 20 rows and they are divided into 4 groups, the first 5 rows will have a group id = 1, and the next 5 rows will have group id = 2 and so on. Each row will have its group id stored in a variable while creating the table.
My task is to give checkboxes to all the rows in a group but make only the first row of a particular group clickable. If the user checks/unchecks the first checkbox of a particular group, all checkboxes of that particular group are checked/unchecked.
I am achieving this by concatenating a counter with the id element of each row and then running a loop through the entire table on each row comparing the current row with its previous row on group id. If the group id of the current row is the same as previous row, it will get the state of checkbox of previous row and make the current checkbox the same state. Nothing is done if the group id of current row is different from previous row.
The problem here is, this logic is working absolutely fine but only once. The checking/unchecking all boxes works only after that it just checks/unchecks that particular box but not for the whole group.
Will provide more info if required. Thanks
function checkBoxTick(){
for(var i = 0; i<$('#grouprowcount').val(); i++){
if(i != 0){
var previd = $('#groupId'+(i-1)).val();
var nextid = $('#groupId'+(i)).val();
if(previd == nextid ){
$("#numid"+(i)).attr("checked", true);
if($("#numid"+(i-1)).is(":checked")){
$("#numid"+(i)).attr("checked", true);
}
else if($("#numid"+(i-1)).is(":not(:checked)")){
$("#numid"+(i)).attr("checked", false);
}
}
}
}
Upvotes: 0
Views: 66
Reputation: 405
Please, check if this is what you need, otherwise I suggest you to show us a snippet of your own code.
var groupCount = 2;
for(var i = 1; i <= groupCount; i++)
$(':checkbox').filter('[name="group-'+i+'"]').not(':first').prop('disabled', true);
$(':checkbox').not(':disabled').change(function() {
var group = $(this).attr('name');
var checked = $(this).prop('checked');
$(':checkbox').filter('[name="'+ group +'"]').prop('checked', checked);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-1" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
<tr><td><input type="checkbox" name="group-2" /></td></tr>
</table>
Upvotes: 1