I want to format column dynamically. datatables has built-in helpers for the same. The code below works :
render: $.fn.dataTable.render.number( ',', '.', 0)
But I am trying to format after creation of table as formatting is dependent on user input. The code below does not work.
$('#mytable').DataTable().column(2).render.number(',', '.', 0);
var oldCurrency = 'usd';
var newCurrency = 'usd';
var myTable = $('#mytable').DataTable({
sDom: 't',
columns:[
{data: 'item', title: 'Item'},
{data: 'descr', title: 'Description'},
{data: 'cost', title: 'Cost', render: function(data, type, row){
var exchangeRate = {usd: 1, eur: 0.87, gbp: 0.78};
row.cost = row.cost*exchangeRate[newCurrency]/exchangeRate[oldCurrency];
return row.cost;
}}
]
});
$('#currency').on('focus', function(){
oldCurrency = this.value;
});
$('#currency').on('change', function(){
newCurrency = this.value;
myTable.draw();
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<select id="currency">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbp">GBP</option>
</select>
<table id="mytable">
<thead>
<th>Item</th>
<th>Description</th>
<th>Cost</th>
</thead>
<tbody>
<tr>
<td>pen</td>
<td>writing tool</td>
<td>5.5</td>
</tr>
<tr>
<td>pencil</td>
<td>wooden stick</td>
<td>4.8</td>
</tr>
<tr>
<td>eraser</td>
<td>piece of rubber</td>
<td>1.2</td>
</tr>
</tbody>
</table>
</body>
</html>