0

It correctly saves the data to the string, but how do I show the data in my table? Why isn't this code working? Javascript code:

$(document).ready(function () {
$.getJSON("http://wt.ops.few.vu.nl/api/32464776",
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
    tr = $('<tr/>');
    tr.append("<td>" + data[i].category + "</td>");
    tr.append("<td>" + data[i].name + "</td>");
    tr.append("<td>" + data[i].amount + "</td>");
    tr.append("<td>" + data[i].location + "</td>");
    tr.append("<td>" + data[i].date + "</td>");
    $('table').append(tr);
}
});
});

HTML code: (first entries are just examples, I need the data I added when I click on submit, to show itself)

<table id="tabel1" class="sortable">
<caption> <strong>Product Inventory List</strong> </caption>
<tr>
    <th> Name </th> <th> Category </th> <th> Amount </th> <th> Location </th> <th> Purchase Date </th>
</tr>
<tr>
    <td> Banana </td> <td> Fruit </td> <td> 1 </td> <td> Amsterdam </td> <td> 2015-11-21 </td>
</tr>
<tr>
    <td> Shirt </td> <td> Clothes </td> <td> 2 </td> <td> Ijsselstein </td> <td> 2015-09-01 </td>
</tr>
<tr>
    <td> Laptop </td> <td> Electronics </td> <td> 1 </td> <td> Aalsmeer </td> <td> 2014-12-31 </td>
</tr>

And link to the script:

<link rel="stylesheet" type="text/css" href="css.css"> <script src= adddata.js></script> 
Nina
  • 1

1 Answers1

0

You're referencing the wrong table: $('table') it should be $('#tabel1') instead.

Here's an example:

$(document).ready(function () {
  $.getJSON("http://wt.ops.few.vu.nl/api/32464776",
  function (data) {
    for (var i = 0; i < data.length; i++) {
        $('#tabel1').append("<tr><td>" + data[i].category + "</td></tr>");
    }
  });
});

EDIT: Actually, the problem is with this line $('<tr/>');, you can see more examples of how you append data to a table here: Add table row in jQuery

Community
  • 1
  • 1
Carlos Martinez
  • 4,350
  • 5
  • 32
  • 62