简体   繁体   中英

populating table with jquery and json

I would like to populate an existing table with json data. I found an example on stackoverflow which does this but with only one column of data. The json data has three sets of data which requires obviously 3 columns. I have experimented with only one row but the jquery code (below) incorrectly displays the table.

<table class="table">
<tr id="row1">
<td = "col1"></td>
<td = "col2"></td>
<td = "col3"></td>

function myFunction() { 

    data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
            {"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];

    $.each(data, function(key, value) {
        $("#row1").eq(key).find('td').text(value.indx);
        $("#row1").eq(key).find('td').text(value.amt);
        $("#row1").eq(key).find('td').text(value.jDate);

    });
}

OUTPUT IN BROWSER: 167 167 167

It is displaying the last field in all three columns. Any advise on how to do get table to display the correct values would be appreciated.

Your code is updating ALL CELLS with value.indx , then with value.amt and finally with value.jDate ... So fast that you only see the final result.

I think what you want to achieve is something more like in this CodePen :

function myFunction() { 

    data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167},
            {"indx":2,"amt":3345.4,"vendor":22,"jDate":168}];

    $.each(data, function(key, value) {
        $("table").find('tr').eq(key).find("td").eq(0).text(value.indx);
        $("table").find('tr').eq(key).find("td").eq(1).text(value.amt);
        $("table").find('tr').eq(key).find("td").eq(2).text(value.jDate);

    });
}
myFunction();

Obviously you have to add rows dynamically into your table, because your data array may contain different amount of objects. Try this code.

Here we have table which is populated with new rows for each element of data array.

 data = [{"indx":1,"amt":234.56,"vendor":11,"jDate":167}, {"indx":2,"amt":3344.4,"vendor":22,"jDate":168}, {"indx":3,"amt":1414.1,"vendor":21,"jDate":169}, {"indx":4,"amt":3441.3,"vendor":31,"jDate":1610}]; $.each(data, function(key, value) { var tr = $("<tr>"); tr.append($("<td>").text(value.indx)); tr.append($("<td>").text(value.amt)); tr.append($("<td>").text(value.vendor)); tr.append($("<td>").text(value.jDate)); $("#table").append(tr); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="table" border="1"> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM