DataTables sum of calculated values
How to apply a calculation on a column which field are already calculated values.
by Richard
HTML
<link rel="stylesheet" href="https://nightly.datatables.net/css/jquery.dataTables.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container">
<br>
<button id="addRow">Add new row</button>
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seat</td>
<td>690</td>
<td>2</td>
<td></td>
</tr>
</tbody>
</table>
<div>
TOTAL: <span class="total"></span>
</div>
</div>
</body>
</html>
CSS
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
JavaScript
var table;
// JSON data from WebSocket (I don't use AJAX)
function addRow(json) {
var row = JSON.parse(json);
var node = table.row.add(row).draw().node();
//$('.total').text(table.column(3).data().map(d => d.total).sum()); // works with price column but not with total column
let countTotal = table.column(3).data().reduce((accumulator, currentValue) => accumulator + currentValue.quantity * currentValue.price, 0);
$('.total').text(countTotal);
}
$(document).ready( function () {
table = $('#example').DataTable({
"columns": [
{ "data": "name" },
{ "data": "price" },
{ "data": "quantity" },
{ "data": null, render: function (data, type, row) { // null is to get all data for computing values, see "Computing values" section at https://datatables.net/manual/data/renderers#Functions
return ((data.price * data.quantity));
}},
],
});
var json = '{"name":"Tyre", "price": 149, "quantity": 2}';
$('#addRow').on( 'click', function () {
addRow(json);
});
// Automatically add a first row of data
$('#addRow').click();
console.log(table.column(1).data());
console.log(table.column(3).data());
} );