Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: detecting if there are no rows left in table

Tags:

jquery

I'm trying to detect if there are any rows left in a table, once none exist, I will display an alert. The following code doesn't seem to work, any ideas? (There will be one row left with the table headers, which is why I used the index 1)

$('.remove_row').live('click', function() {

    //If there are no rows left in table, display alert
    if ( $(this).parent().parent().parent().children('tr:eq(1)').length == 0) {

        alert("no rows left");

    }

    $(this).parent().parent().remove();

});

EDIT: I tried with the remove before the alert, and it triggers every time I remove a row.


EDIT AGAIN: Got it, needed to make the index 2, since it is checking before the final one is actually removed from the DOM.

like image 666
ThinkingInBits Avatar asked Sep 01 '25 09:09

ThinkingInBits


1 Answers

if ( $(this).closest("tbody").find("tr").length === 0 ) {
    alert("no rows left");
}

This finds the cloest parent tbody of the clicked element (a tbody always exists in the DOM). It checks for the length of the tr elements within said tbody. If it equals 0, it will display the alert.

like image 109
Purag Avatar answered Sep 04 '25 05:09

Purag