DataTables example Footer callback

Through the use of the header and footer callback manipulation functions provided by DataTables (headerCallbackDT and footerCallbackDT), it is possible to perform some powerful and useful data manipulation functions, such as summarising data in the table.

The example below shows a footer callback being used to total the data for a column (both the visible and the hidden data) using the column().data()DT API method and column().footer()DT for writing the value into the footer.

First nameLast namePositionOfficeSalary
Total:$3008160 ( $14371710 total)
Airi Satou Accountant Tokyo $162,700
Angelica Ramos Chief Executive Officer (CEO) London $1,200,000
Ashton Cox Junior Technical Author San Francisco $86,000
Bradley Greer Software Engineer London $132,000
Brenden Wagner Software Engineer San Francisco $206,850
Brielle Williamson Integration Specialist New York $372,000
Bruno Nash Software Engineer London $163,500
Caesar Vance Pre-Sales Support New York $106,450
Cara Stevens Sales Assistant New York $145,600
Cedric Kelly Senior Javascript Developer Edinburgh $433,060
Showing 1 to 10 of 57 entries

The Javascript shown below is used to initialise the table shown in this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
$(document).ready(function() {
    $('#example').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( 4 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                } );
 
            // Total over this page
            pageTotal = api
                .column( 4, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
 
            // Update footer
            $( api.column( 4 ).footer() ).html(
                '$'+pageTotal +' ( $'+ total +' total)'
            );
        }
    } );
} );

In addition to the above code, the following Javascript library files are loaded for use in this example: