xtlc
xtlc

Reputation: 1368

Added table row ends up above table instead of in it

My auto-refresh function in jQuery updates a table dynamically. Unfortunately the updated string is always bosted BEFORE the table (above the thead) for some reason I miss to see in my code:

html:

<div class="container"><h1>Refresh Test:</h1></div>
    <div id="table_1" class="container">
        <table class="table" style="width: 100%"> 
            <thead><tr><th>1</th><th>2</th><th>time</th></tr></thead> 
            <tbody>
                <div id="tablerow" > </div>
            </tbody>
        </table>
    </div>

jQuery update function:

<script type="text/javascript">function refreshTable()  {  
    $.get(
        "/foo", "", 
        function(data) {
            $("#tablerow").html("<tr><td>" + JSON.parse(data).D1 + "</td><td>" + JSON.parse(data).D2 + "</td><td>" + JSON.parse(data).D3 + "</td></tr>")
        },
    ) 
};
window.setInterval(refreshTable, 3000)</script>

When inspecting I see the <tr> .... </tr> under the section ::before. Also: If I create the table rows empty before and add per <td> (like this: <tr><td><div id="NAME"></div></td></tr> with #NAME in the script instead of tablerow and only a single value).

Upvotes: 1

Views: 53

Answers (2)

ssilas777
ssilas777

Reputation: 9754

you can try below code..

    <script type="text/javascript">
       function refreshTable()  {  
        $.get(
            "/foo", "", 
            function(data) {
           if($(".table tbody").children().length > 0)){
                $(".table").append("<tr><td>" + JSON.parse(data).D1 + "</td><td>" + JSON.parse(data).D2 + "</td><td>" + JSON.parse(data).D3 + "</td></tr>")
            }
            else{
                $(".table").html("<tr><td>" + JSON.parse(data).D1 + "</td><td>" + JSON.parse(data).D2 + "</td><td>" + JSON.parse(data).D3 + "</td></tr>) 
            } 
            },
         ) 
      };
          window.setInterval(refreshTable, 3000)
    </script>

check this fiddle https://jsfiddle.net/0djn9f15/

Upvotes: 2

Benny Halperin
Benny Halperin

Reputation: 2332

div can’t be the child of tbody. Give tbody the id “tablerow”, remove the div and retry

Upvotes: 1

Related Questions