Reputation: 150
I have this code:
HTML
<table class=tbl>
<tr>
<td>
<input class='c1' type='checkbox'>
<label>Ceckbox1</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
</tr>
</table>
<table class=tbl>
<tr>
<td>
<input class='c1' type='checkbox'>
<label>Ceckbox1</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
<td>
<input class='c2' type='checkbox'>
<label>Ceckbox2</label>
</td>
</tr>
</table>
JavaScript
$('.c2').click(function () {
if ($(this).parent().find('.c2').is(':checked')) {
alert('all are checked');
} else {
alert('none are checked');
}
});
I am trying, with no result, to use jquery to auto-check 'c1' only when all the 'c2' from the same 'tbl' are checked. The count of 'c2' can vary as can the count of 'tbl'.
Upvotes: 6
Views: 1752
Reputation: 48803
$('.c2').click(function () {
var $tbl = $(this).closest('.tbl');
$tbl.find('.c1').prop('checked', $tbl.find('.c2:not(:checked)').length === 0);
});
Upvotes: 0
Reputation: 45121
Try
$('.c2').click(function () {
var all = $(this).closest('.tbl').find('.c2'),
checked = all.filter(':checked');
if (all.length === checked.length) {
alert('all are checked');
} else {
alert('none are checked');
}
});
http://jsfiddle.net/tarabyte/Q6San/
Upvotes: 0
Reputation: 1162
Try the following
$('.c1').click(function () {
if ($(this).parent().find('.c1').is(':checked')) {
alert('all are checked');
$('.tbl input').attr('checked',true);
} else {
alert('none are checked');
$('.tbl input').attr('checked', false);
}
});
Upvotes: 0
Reputation: 146310
This will check if all .c2
checkboxes on the same table are checked:
$('.c2').on('change', function(){
var allCheckboxes = $(this).parents('table').find('.c2');
var allCheckedBoxes = $(this).parents('table').find('.c2:checked');
if(allCheckboxes.length === allCheckedBoxes.length ) {
$(this).parents('table').find('.c1').prop('checked', true);
}
});
Demo: http://jsfiddle.net/maniator/JxCC2/
Upvotes: 0
Reputation: 35973
Try this code it works:
$('.c2').change(function(){
var all = true;
$(this).parent().parent().find('.c2').each(function(index){
if(!($(this).is(':checked'))){
all = false;
}
});
if (all==true){
$(this).parent().parent().find('.c1').attr('checked', true);
}
});
Upvotes: 1
Reputation: 337627
You can see if all the checkboxes are checked by comparing the total number of checkboxes to the number of checked boxes, within the same parent tr
. Try this:
$('.c2').change(function () {
var $parent = $(this).closest('tr');
var allChecked = $('.c2', $parent).length === $('.c2:checked', $parent).length;
$('.c1', $parent).prop('checked', allChecked);
});
Upvotes: 4