Karem
Karem

Reputation: 18103

After adding, resetting/removing table rows in jQuery

<table id="myTable" style="width: 650px;">
  <tbody>
    <tr style="font-weight: bold;">
        <td>Name</td>
        <td>Price</td>
        <td>Supplier</td>
        <td>Amount</td>
        <td>Basket</td>
    </tr>
  </tbody>
</table>

is my HTML.

This is my current jQuery JS:

    $.post('/ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val() }, function(data) {
        data = $.parseJSON(data);
            $('#myTable > tbody:last').append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');
        });
    });

Each time you key up, the above js executes. Now when you are looking for Cookies, and you starts to write, it sends a ajax post with "C" then "Co" then "Coo" etc.

Already at the first ajax call it has found results that are starting with C. Therefore it appends to the table. Now it also found results for "Co" (same results as "C", because theres only Cookies in the db at the moment).

And the same with Coo, Cook, Cooki, Cookie, Cookies... yeah you get the point. And the results of this is alot of tables appending under eachother.

So what i wish to do is like cleaning/removing the <tr>'s thats inside #myTables tbody, before it appends (actually just before the $.post()).

But it should not remove the first <tr>, which is the column headers as you can see in my above html.

How can i do this?

Upvotes: 2

Views: 1371

Answers (1)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

Without changing your html you could write:

var rows = $('#myTable').find('tr');
rows.each(function(index, value) {
  if (index > 0) {
    $(value).remove();
  }
});
$('#myTable > tbody:last').append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');

My recommendation however, would be to use a th for your table header:

<table id="myTable" style="width: 650px;">
  <thead>
    <tr style="font-weight: bold;">
      <td>Name</td>
      <td>Price</td>
      <td>Supplier</td>
      <td>Amount</td>
      <td>Basket</td>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Then your javascript can be:

 $('#myTable > tbody').empty().append('<tr><td>'+b.name+'</td><td>'+b.price+'</td><td></td><td></td></tr>');

Upvotes: 4

Related Questions