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>
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.
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/
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With