Foreach jquery concatenate in table

2

I have an AJAX that in success brings a response :

$(response).each(function(i) {
  alert(response[i]);
  $('#tbody').html(
    "<tr>" +
    "<td>" + response[i].id + "</td>" +
    "<td>" + response[i].nome + "</td>" +
    "</tr>")
});

My HTML:

<tbody id="tbody"></tbody>

But it is overwriting the data, that is, when i=0 looks like this:

<tbody id="tbody">
  <tr>
    <td> 1 </td>
    <td> Maria </td>
  </tr>
</tbody>

when i=1 :

<tbody id="tbody">
  <tr>
    <td> 2 </td>
    <td> João </td>
  </tr>
</tbody>

Expected result:

<tbody id="tbody">
  <tr>
    <td> 1 </td>
    <td> Maria </td>
  </tr>
  <tr>
    <td> 2 </td>
    <td> João </td>
  </tr>
</tbody>
    
asked by anonymous 31.10.2018 / 14:41

1 answer

5

The problem is that you are using .html() and it will replace every iteration. The correct thing is to use append() .

$(response).each(function(i) {
  alert(response[i]);
  $('#tbody').append(
    "<tr>" +
    "<td>" + response[i].id + "</td>" +
    "<td>" + response[i].nome + "</td>" +
    "</tr>")
});     

append() takes what you already have and adds a new one.

    
31.10.2018 / 14:45