Datatables.net Table Column Sum In Footer
Solution 1:
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.
Solution 2:
Mix. Empty replaced to 0
"initComplete": function (settings, json) {
this.api().columns('.sum').every(function () {
var column = this;
var intVal = function (i) {
returntypeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var sum = column
.data()
.reduce(function (a, b) {
returnintVal(a) + intVal(b);
});
$(column.footer()).html('Sum: ' + sum);
});
}
Post a Comment for "Datatables.net Table Column Sum In Footer"