Your table manipulation code needs to be executed only when DataTable is initialized, (see initComplete property).
Also make sure you have <tfoot></tfoot>
block defined in your <table>
otherwise there would be no footer.
Otherwise you were very close to the solution, please see below the corrected code:
var table = $('#ticketTable').DataTable({
'initComplete': function (settings, json){
this.api().columns('.sum').every(function(){
var column = this;
var sum = column
.data()
.reduce(function (a, b) {
a = parseInt(a, 10);
if(isNaN(a)){ a = 0; }
b = parseInt(b, 10);
if(isNaN(b)){ b = 0; }
return a + b;
});
$(column.footer()).html('Sum: ' + sum);
});
}
});
See this JSFiddle for an example.
UPDATE
There is also footerCallback property that lets you defined footer display callback function which will be called on every "draw" event.
The difference between initComplete
and footerCallback
is that initComplete
is called once and footerCallback
on every "draw" event.
If you're displaying the sum for the whole table, initComplete
should suffice. Otherwise if you require to show in the footer data relevant for current page only (as in Footer callback example), use footerCallback
instead.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…