0

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

1 Answer 1

1

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>`);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you but I am getting "TypeError: Cannot read properties of null (reading 'replaceWith')" err I need to call updateRow function inside onMemberListUpdate right ?
sorry the example uses jquery you can do the same without jquery as described here stackoverflow.com/questions/10165262/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.