Recalculate colum on ordering
by Colin Marks
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<input type="text" id="initialInput" value="20"/>
<table id="mytable">
<thead><tr></tr><th>column1</th>
<th>column2</th>
<th>column3</th></tr>
</thead>
<tbody>
<tr>
<td>val1</td>
<td>5</td>
<td></td>
</tr>
<tr>
<td>val2</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>val3</td>
<td>3</td>
<td></td>
</tr>
</tbody>
</table>
JavaScript
// JavaScript source code
// find elements
var initVal = $("#initialInput").val() * 1;
var myTable = $('#mytable').DataTable({
select: {
info: false
},
ordering: true,
columns: [
{
"data": "column1",
"name": "column1",
"className":"text-center",
"orderable": true,
},
{
"data": "column2",
"name": "column2",
"className":"text-center",
"orderable": false,
},
{
"data": "column3",
"type": "formatted-num",
"className":"text-center",
"orderable": true
}
],
"drawCallback": function( settings) {
var tableJq = this.api();
var colTindex = 2;
if (tableJq.rows().count() > 0) {
if (initVal == 0 || typeof initVal == 'undefined') {
return;
}
else {
var tableData = tableJq.rows({order:'current'}).data().toArray();
for (var j = 0; j < tableJq.rows().count() ; j++) {
var smColSource = 0;
for (var i = 0; i < j+1 ; i++) {
smColSource += tableData[i].column2 * 1;
}
tableJq.cell(':eq('+j+')', colTindex).data(initVal * 1 - smColSource * 1);
console.log(tableJq.cell(j, colTindex).data());
}
}
}
}
});