Simple jquery Datatable
Jquery Datatable - updating table
by Rishi Gautam
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>
<button id='btn'>Add and Reload</button>
<table id="myTable" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Number</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS
button {
padding: 5px;
margin-bottom: 5px;
}
JavaScript
var data = [];
var table;
data.push(['1', 'Jervis', '32', 'Richmond', 'Canada']);
data.push(['2', 'Dave Campbell', '32', 'Burnbay', 'Canada']);
data.push(['3', 'Lana Delly', '32', 'Some really big city name', 'Canada']);
table = $('#myTable').DataTable({
data: data
});
$('#btn').on('click', function() {
data.push([randomNumber(), randomString()]);
table.destroy();
table = $('#myTable').DataTable({
data: data,
scrollX: true
});
})
/*
* Helper functions
*/
function randomNumber() {
return Math.floor(Math.random() * 100);
}
function randomString() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}