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'.
Answer: Use the jQuery prop() method You can use the jQuery prop() method to check or uncheck a checkbox dynamically such as on click of button or an hyperlink etc.
$('#envoyer'). click(function(e){ var myArray = new Array(3); for ( var j = 0; j < 3; j++) { var check=$('input:checkbox[name=checkbox'+j+']').is(':checked'); if(check==true) myArray[j]=$('input:checkbox[name=checkbox'+j+']'). val(); // Alert Current Selection // alert('check ' + " " + myArray[j] ); } });
There are two methods by which you can dynamically check the currently selected checkbox by changing the checked property of the input type. Method 1: Using the prop method: The input can be accessed and its property can be set by using the prop method.
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);
});
Example fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With