Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove/hide table's empty column(s), including <th>

How can I hide the column with all empty cells including the title <th> in that column, while leaving the other columns and their titles as it is. Following jquery hides the entire <th>, which is not I want. Here is a sample, where I want to hide only the entire 'Column3' including <th>. Many thanks in advance.

$('table#mytable tr').each(function() {
    if ($(this).children('td:empty').length === $(this).children('td').length) {
        $(this).hide();
    }
});
like image 610
DGT Avatar asked Mar 02 '11 19:03

DGT


1 Answers

If you want to hide the column if all cells (ignoring the header) are empty, you could do something like:

$('#mytable tr th').each(function(i) {
     //select all tds in this column
     var tds = $(this).parents('table')
              .find('tr td:nth-child(' + (i + 1) + ')');
        //check if all the cells in this column are empty
        if(tds.length == tds.filter(':empty').length) { 
            //hide header
            $(this).hide();
            //hide cells
            tds.hide();
        } 
}); 

Sample: http://jsfiddle.net/DeQHs/

Sample 2 (adapted for jQuery > 1.7): http://jsfiddle.net/mkginfo/mhgtmc05/

like image 74
nxt Avatar answered Sep 24 '22 22:09

nxt