sum on 1+ columns in datatables footer using footer_callback?

前端 未结 1 1814
无人及你
无人及你 2021-01-24 04:23

Given this footer_callback datatables example here is my FIDDLE.

This basically sums the total per column for 1 column. Can anyone advise how I can do this for

相关标签:
1条回答
  • 2021-01-24 04:52

    Check out the fiddle here. I'm using the sum plugin. With this approach, you can just add a column index to an array to total it.

    I also added the 'applied' filter so the totals dynamically update when filtering.

    $(document).ready(function() {
    
            // SUM PLUGIN
            jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
                return this.flatten().reduce( function ( a, b ) {
                    if ( typeof a === 'string' ) {
                        a = a.replace(/[^\d.-]/g, '') * 1;
                    }
                    if ( typeof b === 'string' ) {
                        b = b.replace(/[^\d.-]/g, '') * 1;
                    }
    
                    return a + b;
                }, 0 );
            } );
    
            $('#example').DataTable({
                "footerCallback": function () {
                    var api = this.api(),
                        columns = [3, 5]; // Add columns here
    
                    for (var i = 0; i < columns.length; i++) {
                        $('tfoot th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>');
                        $('tfoot th').eq(columns[i]).append('Page: ' + api.column(columns[i], { filter: 'applied', page: 'current' }).data().sum());
                    }
                }
            });
        });
    
    0 讨论(0)
提交回复
热议问题