Monday 16 November 2015

Jquery select all/de select all checkbox

Let us check how we can make select/deselect check box using Jquery. I have explained the same using Angular js 1 and 2 as well. If you want to compare the implementation please check below post as well.

1. Select all/ deselect all check box using Angular js 1
2. Select all/ deselect all checkbox - Angular 2

Create a dynamic checkbox


//Html
<div class="wrapper"></div>
 
//JS
var _html = '<div class="list">
    <label><input type="checkbox" checked class="selectAll"> 
  Countries
    </label>';

var _list = ['USA','India','China','England','Japan'];

for ( var i = 0; i < _list.length; i++ )
{
_html += '<div class="checkbox">
 <label>
 <input type="checkbox" checked class="checkbox" value="' + _list[i] + '"/>' + _list[i] + '
 </label>
 </div>';
}

_html += '</div>'

$('.wrapper').after(_html);
 

Select All/De Select All features



$('.selectAll').change(function(){
  $(".checkbox").find(':checkbox').prop("checked", this.checked);  
});


Now you can see that select all/de select all feature is working fine .But if we unselect one of the checkbox then the master check box also need to uncheck and also if we select all check box master should also checked .For making this possible add below code as well.


$(".checkbox").change(function(){
 
 var _totalChecked = $('.checkbox').find('input:checked').length;
 
 if(_totalChecked == _list.length){
  
  $(".selectAll").prop("checked", true);
 
 }else{
  
  $(".selectAll").prop("checked", false);
 
 }

});

Related Posts

1. Angular select all/de select all checkbox.

2. How to check lowercase in indexOf of an Array

3. Covert string to camel case using javascript

4. How to remove duplicate from an array and get count of duplicated .


No comments :

Post a Comment