JQuery Datatables Sum / Total for Multiple Groups

I have a datatable with 2 rows of a group, and I would like to have a sum / subtotal for one column, for example, the age (it makes no sense, I know;)) of each grouped row.

Here is the JSFiddle .

        $(document).ready(function() {
        var table = $('#example').DataTable({
    "ordering": false,
    "columnDefs": [
                { "visible": false, "targets": [2, 1] }
            ],
            "drawCallback": function(settings) {
                var api = this.api();
                    var rows = api.rows({ page: 'current' }).nodes();
                    var last = null;
                    var columns = [2,1];

                    for (c = 0; c < columns.length; c++) {
                        var colNo = columns[c];
                        api.column(colNo, { page: 'current' }).data().each(function (group, i) {
                            if (last !== group) {
                                $(rows).eq(i).before(
                                    '<tr class="group"><td colspan="4"><h4 style="font-weight: bold !important;">' + group + '</h4></td></tr>'
                                );
                                last = group;
                            }
                        });
                    }
            },
        });
    });
+4
source share
1 answer

You can add "footerCallback" to your .DataTable ({})

 "footerCallback": function ( row, data, start, end, display ) {
        var api = this.api(), data;
        // Remove the formatting to get integer data for summation
        var intVal = function ( i ) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '')*1 :
                typeof i === 'number' ?
                    i : 0;
        };
        // Total over all pages
        total = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
                return intVal(a) + intVal(b);
            }, 0 );
      // Total over this page
        pageTotal = api
            .column( 3, { page: 'current'} )
            .data()
            .reduce( function (a, b) {
                return intVal(a) + intVal(b);
            }, 0 );
        // Update footer
        $( api.column( 3 ).footer() ).html(
            'Total age:'+pageTotal +' ( '+ total +' total)'
        );
      },

I downloaded jsfiddle

You can change the number of "column (3)" to change the column that you would like to summarize.

Hope this helps :)

0
source

Source: https://habr.com/ru/post/1657782/


All Articles