Warm tip: This article is reproduced from stackoverflow.com, please click
datatable jquery

How to add pagination after each group in jQuery Datatable?

发布于 2020-03-27 10:17:57

Working on data tables and everything seems great. I am using the rowGroup and it works great and showing me the grouping properly. Also using startRender to find and show group vice calculations.

My problem is that pagination affects my calculations; if display length is set to 10, and a group have 17 rows, in start render calculation it gives the calculation result of first 10 rows in page one and calculation remaining 7 in next page.

1) Either I want to make the calculations irrespective of page, it is needed the calculation done in the all 17 rows under that group

2) OR I need to adjust pages based on groups. that is group 1 on page 1, group 2 on page 2 and so on..

var data_table = $('#myTable').DataTable( {

 order: [[0, 'asc'], [1, 'asc']],
 "displayLength": 25,
 rowGroup:{
  dataSrc: [0, 1],
  startRender: function ( rows, group ) {

   var clickTotal = rows
   .data()
   .pluck(3)
   .reduce( function (a, b) {
    return parseInt(a) + parseInt(b);
  });

            var ageCTR = rows
            .data()
            .pluck(5)
            .reduce( function (a, b) {
             return parseInt(a) + parseInt(b);
               });

            return $('<tr>')
            .append( '<td>'+group+'</td>' )
            .append( '<td>'+clickTotal+'</td>' )                    
            .append( '<td>'+ageCTR +'</td></tr>' );

          }
        },
        columnDefs: [ {
          targets: [ 0, 1,5 ],
          visible: false
        },
        { orderable: false, targets: [2,3,4] } ],
      } );
Questioner
Sangeetha
Viewed
141
Sangeetha 2019-07-04 17:32

After studying Datatable features for a good amount of time, found a solution to my problem.

The rows parameter in startRender and endRender cover only those rows displayed on the current page. To calculate all rows then we will need to use filter() to filter the table based on the group and calculate the sum. Here is my updated code. Hope someone will find it helpful.

[Because I used multilevel grouping based on column 0 & column 1,both of those columns are compared to the group value in the filter function.]

var clickTotal = $('#myTable').DataTable()
     .rows()
     .data()
     .filter( function ( data, index ) {

       return (data[0] == group || data[1] == group) ? true : false;
     } )
     .pluck(5)
     .sum();