On a template, I have a websocket connection which sends to the page data every second. So every second a new array of arrays like the one below is received, just with different values. I'm trying to show this data on a datatable. The problem is that I need to override the data on the table, so every time I receive a new array of arrays, the previous data that was on the table must be overwritten with the new records.
var data = [
[1, 5],
[9, 3],
[71.55, 17],
[1800, 20],
[713, 3],
]
Here is what I tried:
$.each(data, function(key,value) {
$('#mytable').append('<tr><td>'+value[0]+'</td><td>'+value[1]+'</td></tr>')
})
The problem with this code is that, although it will show the data correctly, every time I receive a new array, instead of overwriting the old one it will just append the data.
I also tried:
$.each(data, function(key,value) {
$('#mytable').html('<tr><td>'+value[0]+'</td><td>'+value[1]+'</td></tr>')
})
But this is not going to work, since it will only loop through the array and only show one record of the array at time.
Here is the table:
<table id="mytable" class="pos-table table table-striped table-hover">
<thead>
<tr>
<th>RATE</th>
<th>AMOUNT</th>
</tr>
</thead>
</table>
You must generate the dataTable in a variable, then you can destroy it, add the rows and again in the variable create the dataTable
tb.destroy();
// insert rows
tb=$('#mytable').DataTable();
<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js"></script> </head> <body> <table id="mytable" class="pos-table table table-striped table-hover"> <thead> <tr> <th>RATE</th> <th>AMOUNT</th> </tr> </thead> </table> <button onclick="add();">add</button> </button> <script> var data = [ [1, 5], [9, 3], [71.55, 17], [1800, 20], [713, 3], ] var tb = $('#mytable').DataTable(); $(document).ready(function() { add(); }); function add(table) { tb.destroy(); $.each(data, function(key, value) { $('#mytable').append('<tr><td>' + value[0] + '</td><td>' + value[1] + '</td></tr>') }) tb = $('#mytable').DataTable(); } </script> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.