DataTables footer callback example

Preamble

DataTables using the header and footer callback manipulation functions (fnHeaderCallback() and fnFooterCallback()) you can perform some powerful and useful data manipulation. The example given below shows how a callback function can be used to total up visible (and hidden) data, taking into account all of DataTable's features (pagination, filtering etc).

Live example

Rendering engineBrowserEngine versionCSS gradeMarket share (%)
Total:16.66% (100% total)
Gecko Firefox 1.0 1.7 A 0.1
Gecko Firefox 1.5 1.8 A 0.5
Gecko Firefox 2.0 1.8 A 7
Gecko Firefox 3.0 1.9 A 9
Gecko Camino 1.0 1.8 A 0.01
Gecko Camino 1.5 1.8 A 0.01
Gecko Netscape 7.2 1.7 A 0.01
Gecko Netscape Browser 8 1.7 A 0.01
Gecko Netscape Navigator 9 1.8 A 0.01
Gecko Mozilla 1.0 1 A 0.01
Showing 1 to 10 of 57 entries

Warning! The market share information given in this table is fabricated using a combination of (mild) judgement, the BBC Browser Statistics information and statistics from TheCounter.com. THe lowest usage given to anyone browser is 0.01 for reasons of this example.

Initialisation code

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
$(document).ready(function() {
    $('#example').dataTable( {
        "fnFooterCallback": function ( nRow, aaData, iStart, iEnd, aiDisplay ) {
            /*
             * Calculate the total market share for all browsers in this table (ie inc. outside
             * the pagination)
             */
            var iTotalMarket = 0;
            for ( var i=0 ; i<aaData.length ; i++ )
            {
                iTotalMarket += aaData[i][4]*1;
            }
             
            /* Calculate the market share for browsers on this page */
            var iPageMarket = 0;
            for ( var i=iStart ; i<iEnd ; i++ )
            {
                iPageMarket += aaData[ aiDisplay[i] ][4]*1;
            }
             
            /* Modify the footer row to match what we want */
            var nCells = nRow.getElementsByTagName('th');
            nCells[1].innerHTML = parseInt(iPageMarket * 100)/100 +
                '% ('+ parseInt(iTotalMarket * 100)/100 +'% total)';
        }
    } );
} );

Other examples