Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a row that containing empty cell

For the table below, all cell under row2 (tr class="row2") is empty, how to check the row with empty cell and only hide (display: none) it?

<table>
<tr class="row1">
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr class="row2">
<td></td>
<td></td>
<td></td>
</tr>
...
<tr class="row100">
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
</table>
like image 629
Charles Yeung Avatar asked Jul 11 '11 10:07

Charles Yeung


People also ask

How do I hide a specific row?

Hiding Rows Select a cell within the row(s) to be hidden. On the Home command tab, in the Cells group, click Format. From the Format menu, in the Visibility section, select Hide & Unhide » Hide Rows. The row is hidden.


2 Answers

With the following jQuery script you will loop through all table rows, check all their colums and see if any of them is not empty.

If none of them is not empty it will hide the row.

$('table tr').each(function(){

    var hide = true;
    $('td',this).each(function(){

        if($(this).html() != '')
            hide = false;

    });

    if(hide)
        $(this).hide();

});

Excuse me, it's supposed to be .html() not .val()

Here is a jsfiddle example: http://jsfiddle.net/dYkLg/

Here is a shorter version actually, this works by checking if the amount of empty colums is equal to the total amount of colums within that row directly checking if there are any non-empty colums in the current row:

$('table tr').each(function(){

    if(!$('td:not(:empty)',this).length)
        $(this).hide();

});

Updated thanks to Tom Hubbard

With the jsfiddle: http://jsfiddle.net/dYkLg/2/

like image 75
Kokos Avatar answered Nov 15 '22 12:11

Kokos


There are at least two ways to do this.

First, if all the <td> elements are empty, then the inner text of the <tr> element will only consist of whitespace, so you can use $.trim() with filter() and write:

$("tr").filter(function() {
    return $.trim($(this).text()) == "";
}).hide();

You can also use the :not(), :has() and :empty selectors to explicitly match the <tr> elements that only contain empty <td> elements:

$("tr").not(":has(td:not(:empty))").hide();
like image 44
Frédéric Hamidi Avatar answered Nov 15 '22 10:11

Frédéric Hamidi