Reputation: 187
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
Reputation: 382696
Try:
if( $(this).closest('tr').is('tr:only-child') ) {
alert('cannot delete last row');
}
else {
$(this).closest('tr').remove();
}
Upvotes: 5
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.'");
}
});
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.");
}
});
Upvotes: 2
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