0

So I am pretty much brand new to JSON and fairly new to jquery. I've been trying to learn how to generate an HTML table based on the JSON data. But more importantly, I'm going to have multiple tables with different JSON arrays inside of them.

So using the solution given here, I am successfully able to generate the data into a table, but since no where does it specify which table to generate it into, it generates the data into every table on the page. I've been trying to figure out where to add the specific table ID's but everywhere I place them seems to be wrong.

Base code that works but puts it into every table:

    var tr;
    for (var i = 0; i < cte.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + cte[i].accountName + "</td>");
        tr.append("<td>" + cte[i].advisor + "</td>");
        tr.append("<td>" + "Link".link(cte[i].link) + "</td>");
        $('table').append(tr);
    }

My html table code:

<table id="cteTable">
    <tr>
        <th>Account Name</th>
        <th>Advisor</th>
        <th>Links</th>
    </tr>
</table>

<table id="saTable">
    <tr>
        <th>Account Name</th>
        <th>Advisor</th>
        <th>Links</th>
    </tr>
</table>

And when I try doing

tr = $('#cteTable <tr/>');
or
tr = $('#cteTable tr');

Instead of generating into one table, it doesn't create anything. I know this problem I'm having is due to a lack of knowledge of jquery and json. So any help or guidance in the right direction would be greatly appreciated.

Community
  • 1
  • 1
Ethan
  • 141
  • 1
  • 2
  • 9

1 Answers1

0

The first part of

tr = $('<tr/>');

Is unnecessary, it returns nothing, to fetch an html element using jquery you simply put it's tag name / class name / Id inside the quotes.

$('table')
$('.class') 
$('#id') 

To put your generated tr (which is practically an html in the form of a string) into the table you use the append function on the table like so

$('#tableID').append(tr) 

When you're using the table tag name it takes all the tables on the current page and appends your tr to them.

Oryan Moshe
  • 139
  • 8