开发者

jQuery Don't Delete Last Table Row

开发者 https://www.devze.com 2023-03-20 06:28 出处:网络
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 t

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 开发者_JAVA百科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();
}


Try:

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


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消