moses toh
moses toh

Reputation: 13172

How to add checkbox in datatables for row grouping?

My code is like this : http://jsfiddle.net/rkovmhkp/3/

     ...

       }).rowGrouping({
                    fnOnGrouped: function(groups){
                        console.log("Groups", groups);

                        for(key in groups){
                            if(groups.hasOwnProperty(key)){
                               $(groups[key].nGroup).css('background-color', '#F99');
                            }
                        }                   
                    }
                }); 

      ...

I want add checkbox in the upper left corner. When user check the checkbox, The system will show row grouping datatables. When user uncheck the checkbox, The system will show datatables without row grouping. Thank you

Upvotes: 0

Views: 562

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

SOLUTION

Use the code below:

$(document).ready(function () {    
   initTable(true);

   $('.btn-row-grouping-enable').on('click', function(){       
      if(!this.checked){ 
          removeRowGrouping('#example');
      }

      initTable(this.checked);          
   });

});

function initTable(hasRowGrouping){   
     $('#example').dataTable({
         "bDestroy": true,
         "bLengthChange": false,
         "bPaginate": false,
         "bJQueryUI": true,
         "fnCreatedRow": function (nRow, aData, iDataIndex){
             $(nRow).css('background-color', /*oData.colour*/ '#99F');
         }
     });

     if(hasRowGrouping){
        $('#example').dataTable().rowGrouping({
           fnOnGrouped: function (groups) {
              console.log("Groups", groups);

              for (key in groups) {
                 if (groups.hasOwnProperty(key)) {
                     $(groups[key].nGroup).css('background-color', '#F99');
                 }
              }
          }
        });
     }
}

// Remove rowGrouping plugin
function removeRowGrouping(selector){
   var oSettings = jQuery(selector).dataTable().fnSettings();

   for (f = 0; f < oSettings.aoDrawCallback.length; f++) {
      if (oSettings.aoDrawCallback[f].sName == 'fnRowGrouping') {
           oSettings.aoDrawCallback.splice(f, 1);
           break;
      }
   }

   oSettings.aaSortingFixed = null;              
}

DEMO

See this jsFiddle for code and demonstration.

LINKS

Upvotes: 1

Related Questions