Checkbox

by Lucaskazama

HTML

<table class="table">
  <tr>
    <td>
      <input type="checkbox" class="checkAll" data-target="checkbox-primary"/>
      <input type="checkbox" class="checkbox checkbox-primary"/>
      <input type="checkbox" class="checkbox checkbox-primary"/>
      <input type="checkbox" class="checkbox checkbox-primary"/>
      <input type="checkbox" class="checkbox checkbox-primary"/>
    </td>
  </tr>
</table>
  
<table class="table">  
  <tr>
    <td>
      <input type="checkbox" class="checkAll" data-target="checkbox-second"/>
      <input type="checkbox" class="checkbox checkbox-second"/>
      <input type="checkbox" class="checkbox checkbox-second"/>
    </td>
  </tr>
</table>

JavaScript

var valCheck;
var checkAux = {};
var checkAll
$(".checkAll").each(function() {
	checkAux[$(this).attr('data-target')] = {
  	total:	$('.'+$(this).attr('data-target')).length,
    count: 0,    
	}
})
$(".checkAll").on("change", function() {
	valCheck = $(this).prop("checked");
	$('.'+$(this).attr('data-target')).each(function() {
    	$(this).prop("checked", valCheck);
  });
});
$(".checkbox").on("change",function(){
	checkAll = $(this).parents('.table').find('.checkAll')
	console.log($(this).parents('.table'))
  if($(this).prop('checked')) {
		checkAux[checkAll.attr('data-target')].count++;
    
    if(checkAux[checkAll.attr('data-target')].count == checkAux[checkAll.attr('data-target')].total){
      checkAll.prop('checked', true)
    }	
  } else {
		checkAux[checkAll.attr('data-target')].count--;
    checkAll.prop('checked', false)
  }
	
});