Search code examples
jqueryremoveall

Stop removal of whole table when rows still exist


I have the below code, which does two things:

  1. Checks dates in each table row and removes the row if the date is in the past
  2. If all dates in a table are in the past, remove the entire table

However, the second thing isn't working properly. Instead of only removing the table when all rows of the table have dates in the past, as soon as one row has a date in the past, it is removing the whole table, even if there are multiple rows still with dates in the future.

I've setup a Fiddle so can you see this. http://jsfiddle.net/g6a2nt0k You'll notice there are two dates in the table... one in the past, one in the future, so it should still be showing the one in the future, but instead it hides the entire table.

$(function(){
$('.production-date').each(function(key,value){
    var currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    var date = new Date($(value).text());
    if(date < currentDate){
        var currenttable = $(value).parent().closest('table');
        $(value).parent().remove();
        var count = $(currenttable).children('tr').length;
        if(count<=2) { $(currenttable).remove(); }
    }
});

});

Any advice would be appreciated.


Solution

  • This line is returning 0:

    var count = currenttable.children('tr').length;
    

    Why? Because the browser adds a tbody tag around the contents of the table, so there are really no tr elements which are children/direct descendands of the table. That's why this returns 0.

    Change it to this:

    var count = currenttable.find('tr').length;