Dynamic footer and sum only some columns
Dynamic footer and sum only some columns
itajackass
Posts: 162Questions: 48Answers: 3
I've a datatable with columns created dynamically based on an ajax response. I've have to create then the footer and sums columns with only class sum. (I've added class sum correctly on thead columns i need)
With with it works for ALL columns:
nFooterCallback: function(row, data, start, end, display) {
var api = this.api();
var footer = $(this).append('<tfoot><tr></tr></tfoot>');
this.api().columns().every(function () {
var column = this;
var sum = column
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
$(footer).append('<th class="text-right">'+sum+'</th>');
});
}
So I tried this for only columns with class sum but it doesn't work:
fnFooterCallback: function(row, data, start, end, display) {
var api = this.api();
var footer = $(this).append('<tfoot><tr></tr></tfoot>');
this.api().columns().every(function () {
var column = this;
if ( $(this).hasClass("sum") ) { // <--- check ???
var sum = column
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
} else {
var sum = "";
}
$(footer).append('<th class="text-right">'+sum+'</th>');
});
}
How can i check if a column (using api) has a className?
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Hi itajackass,
The last example on this page looks like what you're trying to do. Here, the class is being filtered earlier, in the columns method.
Cheers,
Colin
Hi, thanks for the reply. But it is not what i'm looking for, cause I'll have to loop for EVERY columns (not only with class sum). And calculate the total using the var = sum where columns has class sum, otherwise sum = "".
Hi itajackass,
Trying again! Here's another example I just knocked out.
There's a couple of differences to yours.
You said you added the class to the thead element, but you're not checking there for the class, you're checking the column as a whole.
the scope of sum (I've called mine ourSum). You're declaring it in blocks, but then using outside of those blocks. I don't think it'll make a difference (with
let
it will, butvar
is more tolerant to scoping), but worth changing.Hope that helps and gives better results!
Cheers,
Colin
Thank you colin! This is what I'm looking for!
if ($(column.header()).hasClass('sum'))