Sum calculated column
Sum calculated column

Hi,I have difficulty to have the sum of the column itself calculated.
Exepmle result:
[object Object], [object Object], [object Object], [object Object], [object Object]....
ajax: "php/table1.php",
columns: [
{"data": "name"},
{"data": "table2", render: function (data, row) {
return data.reduce( function (a, b) {
return a + (b.amount)*1; }, 0 ).toFixed(2)+' €';}
},
],
footerCallback: function ( tfoot, data, start, end, display ) {
var api = this.api();
// Total amount
$( api.column(2).footer() ).html(api.column(2)
.data()
.reduce( function ( a, b ) {
return a + b;
}, 0 )
)
},
This discussion has been closed.
Replies
It's probably because you're using object based data. We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.
Cheers,
Colin
Hi, I do not master the javavascript, I have prepared an example could you take a look, thank you
http://live.datatables.net/kitizove/1/edit
http://live.datatables.net/kitizove/2/edit
Hi @Tony S ,
The problem is because
table.column(3).data()
returns an a 2D array - you resolve this in yourcolumns.render
function, so you need to either do something like that, or usecells().render()
.The second option is the easiest, see your example modified here.
Cheers,
Colin
Thank you very much Colin, it works very well . I did not think of the solution with cells (). Render () for lack of experience.
I have one last question.
I would like to divide the column (3) by the column (2) using "columnDefs" but I can not . Do you have any idea please ? http://live.datatables.net/kitizove/5/edit
Do you mean in the footer, or in the column itself?
In the column itself. ( in column 4 Coef )
I really have trouble arranging both functions !
The place to do that would be in
createdRow
- see your modified example here. It's showing how to get the values in the cells - I'll leave it as an exercise for you to do the sumsDifficult exercise

I was convinced that we should use data: null or columnDefs: but I'm going to look at the problem today
Hi @Tony S ,
I set myself a morning challenge to do it
Here it is - it seems the
createdRow
did work, but it meant the field wasn't searchable. By doing the sums again in thecolumns.render
it meant that column is still filterable.Hope that does the trick,
Cheers,
Colin
Dear Colin, thank you for your valuable help.
It works perfectly.
The use of two variables in the same function is the best solution, but for lack of experience I have not arrived.
Again thank you very much and I am more and more impressed by Datatables, Editor and the forum team ! Good luck in your project.