Labels

Monday, November 24, 2014

select2 selectable group and Select All function

Hi All,

If you want to select all the child element when selecting the group name, using select2 this is the post for you.  I have added the select All chcekbox also.

here is the html part you need to add.
<input type="hidden" id="fruitSelect" value="" style="width:300px;" /><br />
<br/><input type="checkbox" id="checkbox" />Select All
<br />
<button type="button" id="showValue">Show Value</button><br />
<br />
<div id="output">
</div> 


add the following to the Javascript  file, inside the $document.ready function.
 var FRUIT_GROUPS = [  
   {  
     id: '',  
     text: 'Citrus',  
     children: [  
       { id: 'c1', text: 'Grapefruit' },  
       { id: 'c2', text: 'Orange' },  
       { id: 'c3', text: 'Lemon' },  
       { id: 'c4', text: 'Lime' }  
     ]  
   },  
   {  
     id: '',  
     text: 'Other',  
     children: [  
       { id: 'o1', text: 'Apple' },  
       { id: 'o2', text: 'Mango' },  
       { id: 'o3', text: 'Banana' }  
     ]  
   }  
 ];  
 $('#fruitSelect').select2({  
   multiple: true,  
   placeholder: "Select fruits...",  
   data: FRUIT_GROUPS,  
   query: function(options) {  
     var selectedIds = options.element.select2('val');  
     var selectableGroups = $.map(this.data, function(group) {  
       var areChildrenAllSelected = true;  
       $.each(group.children, function(i, child) {  
         if (selectedIds.indexOf(child.id) < 0) {  
           areChildrenAllSelected = false;  
           return false; // Short-circuit $.each()  
         }  
       });  
       return !areChildrenAllSelected ? group : null;  
     });  
     options.callback({ results: selectableGroups });  
   }  
 }).on('select2-selecting', function(e) {  
   var $select = $(this);  
   if (e.val == '') {  
     e.preventDefault();  
     $select.select2('data', $select.select2('data').concat(e.choice.children));  
     $select.select2('close');  
   }  
 });  
 $('#showValue').click(function() {  
   $('#output').text($('#fruitSelect').val());  
 });  
 $("#checkbox").click(function(){  
  if($("#checkbox").is(':checked') ){  
  $('#fruitSelect').select2("val", "");  
  for(var index in FRUIT_GROUPS){  
    $('#fruitSelect').select2('data', $('#fruitSelect').select2('data').concat(FRUIT_GROUPS[index].children));  
  }}else{  
      $('#fruitSelect').select2("val", "");  
    }  
  });   

Demo

I have added the demo for the easiness of understanding.  I haven't describe the code much since its easy to understand. if you have any questions feel free to ask.

Have Fun.