0

I am creating a table that has api data.

This is my js file fetching data:

  $(document).ready(function(){
    $.getJSON(endpoint, function(data){
      var topAgent = [];
      $.each(data, function(key, value){
        topAgent.push ("<tr>");
        topAgent.push ("<td>" + value.agentId + "</td>");
        topAgent.push ("<td>" + value.firstName + "</td>");
        topAgent.push ("</tr>");
      }); 
        $('#topAgents').append(topAgent);
      console.log(topAgent);
    });
  });

When I am checking the console log, it seems fine.

0: "<tr>"
1: "<td>5</td>"
2: "<td>Glenn</td>"
3: "</tr>"
4: "<tr>"
5: "<td>6</td>"
6: "<td>Glenell</td>"
7: "</tr>"

But when I inspect element, the table row element closes automatically:

<tr></tr>
<td>5</td>
<td>Glenn</td>
<tr></tr>
<tr></tr>
<td>6</td>
<td>Glenell</td>
<tr></tr>

I tried to remove the table row element in the js file but the outcome is all the data are aligned together. I also tried to combine the table row element along with the Table Data Cell element but it still automatically closes.

What could cause the problem and what are the possible solutions?

1 Answers1

0

The line topAgent.push ("</tr>"); is causing an issue because since it is inside .each() method <tr> will get close everytime after the data gets filled inside value.agentId and value.firstName

Use append instead:

$(function() {
       $.each(data, function(key, value){
        var $tr = $('<tr>').append(
            $('<td>').text(value.agentId),
            $('<td>').text(value.firstName)
        );
        $('#topAgents').append(topAgent);
    });
});

Inspired from: https://stackoverflow.com/a/17724264/6029001

Rohan Rao
  • 2,505
  • 3
  • 19
  • 39