Reputation: 351
I was trying to make table using JavaScript. I have created a function makeTable to generate table data each time it is been called. My Code -
<table class="table table-striped">
<tr>
<th>User Name</th>
<th>Audio</th>
<th>Video</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
function onMemberListUpdate(members) {
console.log("member updated")
buildTable(members);
}
function buildTable(data){
console.log("build table function called", data);
var table = document.getElementById('myTable');
for(var i =0; i<data.length; i++){
var row = `<tr> <td>${data[i].name}</td> <td>${data[i].audio_muted}</td> <td>${data[i].video_muted}</td> <td><button class="btn btn-primary">Audio</button></td>`
table.innerHTML += row;
}
}
Issue that I am facing here is whenever member list updates and onMemberListUpdate
function gets called it calls buildTable
function that makes new row each time I don't want to create new row each time instead I want to update the existing table data. How can I achieve this thing please help
Upvotes: 0
Views: 4586
Reputation: 2220
Consider marking each row with an attribute that you can use to find it later when you need to update it.
You can (for example) add class="item-id-${data[i].id}"
to the tr
(as below)
function buildTable(data){
console.log("build table function called", data);
var table = document.getElementById('myTable');
for(var i =0; i<data.length; i++){
var row = `<tr class="item-id-${data[i].id}"> <td>${data[i].name}</td> <td>${data[i].audio_muted}</td> <td>${data[i].video_muted}</td> <td><button class="btn btn-primary">Audio</button></td>`
table.innerHTML += row;
}
}
then you can call updateRow
and in that function you can get the row by doing $(".item-id-123")
and you can create new html that replaces it, so something like this:
function updateRow(data) {
$(`.item-id-${data.id}`).replaceWith(`
<tr class="item-id-${data.id}">
<td>${data.name}</td>
<td>${data.audio_muted}</td>
<td>${data.video_muted}</td>
<td><button class="btn btn-primary">Audio</button></td>
</tr>`);
}
Upvotes: 1