Dave
Dave

Reputation: 187

jQuery Don't Delete Last Table Row

Please forgive me, I'm new to web programming. I just started with jQuery yesterday and I need a bit of help. I need to make sure that a user cannot delete the last row of a table. I am able to use the following successfully:

$(this).closest('tr:not(:only-child)').remove();

But I would like to display an alert message if the row is the last row instead of just not doing anything. I tried the following, but it did not work:

if( $(this).closest('tr:only-child') ) {
    alert('cannot delete last row');
}
else {
    $(this).closest('tr').remove();
}

Upvotes: 4

Views: 2763

Answers (3)

Sarfraz
Sarfraz

Reputation: 382696

Try:

if( $(this).closest('tr').is('tr:only-child') ) {
    alert('cannot delete last row');
}
else {
    $(this).closest('tr').remove();
}

Upvotes: 5

David Thomas
David Thomas

Reputation: 253318

To delete rows but allow any row to be the last (non-deletable) row:

$('td').click(
    function(){
        if ($(this).closest('table').find('tr').length > 1) {
            $(this).closest('tr').remove();
        }
        else {
            alert("Can't delete rows of class 'noDelete.'");
        }
    });

JS Fiddle demo.

To delete any rows except those of a 'noDelete' class-name:

$('td').click(
    function(){
        if (!$(this).closest('tr').hasClass('noDelete')) {
            $(this).closest('tr').remove();
        }
        else {
            alert("Can't delete the last row.");
        }
    });

JS Fiddle demo.

Upvotes: 2

a'r
a'r

Reputation: 36999

How about counting the number of <tr> elements in the table's <tbody> using this:

$(this).closest('tbody').children('tr').length

Upvotes: 0

Related Questions