Jefsama Jefsama - 3 months ago 31
jQuery Question

Datatables Complex header + sum api not working

Im having trouble in combining Complex Header + sum() of datatables.

JS

$('#mainTable').DataTable({
"initComplete": function () {
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);
});
}
});


Check this pen for full code:

http://codepen.io/JefMari/pen/mEYXya

Answer

The problem isn't the header, it is the strong-tag around your numbers. Strip the numbers for the calculation, with a regex for example.

var stripRegex = /<.*?>/g;

$('#mainTable').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.replace(stripRegex, ''), 10);
                   console.log(a);
                   if(isNaN(a)){ a = 0; }

                   b = parseInt(b.replace(stripRegex, ''), 10);
                   if(isNaN(b)){ b = 0; }

                   return a + b;
               });

            $(column.footer()).html(sum);
        });
    }
});