Jquery auto-check checkbox from the same table

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 try, without any results, to use jquery to automatically check for 'c1' only when all “c2” from the same “tbl” are checked. Counter "c2" can change in the same way as counter "tbl".

+6
source share
6 answers

Try using this code:

Demo

 $('.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); } }); 
+1
source

You can check if all the checkboxes are checked by comparing the total number of checkboxes with the number of checked cells inside the same parent tr . Try the following:

 $('.c2').change(function () { var $parent = $(this).closest('tr'); var allChecked = $('.c2', $parent).length === $('.c2:checked', $parent).length; $('.c1', $parent).prop('checked', allChecked); }); 

Script example

+4
source

This will check if all .c2 flags are .c2 in the same table:

 $('.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/

0
source
 $('.c2').click(function () { var $tbl = $(this).closest('.tbl'); $tbl.find('.c1').prop('checked', $tbl.find('.c2:not(:checked)').length === 0); }); 

Demo

0
source

Try to execute

  $('.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); } });​ 
0
source

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/

0
source

All Articles