Reputation: 6320
How can I use jQuery to remove all row from a dynamic table like this:
HTML CODE:
<table id="myTable" border="1">
<th style="width:100px;">Barangays</th>
<th style="width:140px;">Lat</th>
<th style="width:140px;">long</th>
<tbody>
<tr></tr>
</tbody>
</table>
I have this code to append <td>
to the table:
JS CODE:
$('tr.' + this.id).html('<td>' + this.title + '</td><td>' + this.getPosition().lat().toFixed(6) + '</td><td>' + this.getPosition().lng().toFixed(6) + '</td>');
Now I need a click function to remove all added rows but keep the first row in the table like before.
Upvotes: 0
Views: 2324
Reputation: 19882
You can also use eq
of jquery
var first = $('#myTable tbody tr').eq(0); // Take the first row
$('#myTable tbody tr').remove(); //remove all rows
$('#myTable tbody').html(first); //put first row again
Upvotes: 1
Reputation: 15767
Use this:
$(document).ready(function() {
$("#myTable").find("tr:gt(0)").remove();
});
OR
if ($("table tr").length != 1) {
$("table tr:last").remove();
}
Upvotes: 3
Reputation: 388316
First the HTML is invalid th should be the child of a tr
element.
To remove the rows try
$('#myTable tr').slice(1).remove()
Change your html to
<table id="myTable" border="1">
<thead>
<tr>
<th style="width:100px;">Barangays</th>
<th style="width:140px;">Lat</th>
<th style="width:140px;">long</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
then
$('#myTable tbody tr').remove()
Upvotes: 4