Behseini
Behseini

Reputation: 6320

Removing All Rows of a Dynamic Table but First Row

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

Answers (4)

Muhammad Raheel
Muhammad Raheel

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

Demo

Upvotes: 1

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

Use this:

$(document).ready(function() {
       $("#myTable").find("tr:gt(0)").remove();
    });

DEMO

OR

if ($("table tr").length != 1) {
     $("table tr:last").remove();
}

Upvotes: 3

nrsharma
nrsharma

Reputation: 2562

Try this

$('#myTable tr').not(':first').remove();

Upvotes: 1

Arun P Johny
Arun P Johny

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

Related Questions