Foreach jquery concatenate in table

Asked

Viewed 53 times

0

I have a AJAX that in the 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, ie, when i=0 gets 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>

1 answer

4


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

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

The append() take what you already have and add a new.

  • 1

    Gilmar, could you add links to the official documentation to make your response even better

  • Link to the documentation append jquery. http://api.jquery.com/append/

  • I meant edit your answer, but that’s okay. I add.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.