Adding a total in the footer.

Adding a total in the footer.

danangeloalcanardanangeloalcanar Posts: 8Questions: 3Answers: 0

Hello Forums,

I am using DataTables for the first time. I came to this problem where I need the sum of rows in the footer.

I have tried the footer callback, but I can't make it work. Would you help achieve this? Please guide where I might be wrong.

Here is my code.

/* Data tables*/
$('#table-summary-per-customer').DataTable({
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 4 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Total over this page
pageTotal = api
.column( 4, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column( 4 ).footer() ).html(
'$'+pageTotal +' ( $'+ total +' total)'
);
}
});

And my HTML

<table id="table-summary-per-customer">
<thead>
<th>Customer</th>
<th>Month</th>
<th>Year</th>
<th>Net Sales</th>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
<?php foreach ($test as $result): ?>
<tr>
<td><?php echo $result['Customer']; ?></td>
<td><?php echo $result['Month']; ?></td>
<td><?php echo $result['Year']; ?></td>
<td><?php echo $result['NetSales']; ?></td>
</tr>
<?php endforeach ?>
</tbody>
</tfoot>
</table>

Thanks a lot. I appreciate it . :)

1.PNG 16.9K

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 62,241Questions: 1Answers: 10,211 Site admin
    Answer ✓

    The HTML doesn't look valid. There is a spare </tfoot> in there and no tr for the header row.

    Run your page through the W3C validator - DataTables assumes valid HTML will be used.

    Allan

  • danangeloalcanardanangeloalcanar Posts: 8Questions: 3Answers: 0

    Thanks Allan. I'll get back to you to give feedback.

  • danangeloalcanardanangeloalcanar Posts: 8Questions: 3Answers: 0

    Thanks for your help Allan. You are a great help. :)

This discussion has been closed.