user7560542
user7560542

Reputation: 547

How do you hide tables with no visible rows with JQuery?

This is what I've got so far, but the second line does not work because apparently you can't concatenate this with a selector:

$(".report-table").each(function () {
    var numOfVisibleRows = $(this + 'tr:visible').length;
    if (numOfVisibleRows == 0)
        $(this).hide();
    else
        $(this).show();
});

Any ideas?


Edit: here is the HTML for the table. There will be multiple tables like this and sometimes I will have hidden all of the table's rows with JQuery hide():

<table class="report-table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Weather Report</td>
            <td>This report lists weather data.</td>
        </tr>
    </tbody>
</table>

Upvotes: 0

Views: 774

Answers (3)

Raptord
Raptord

Reputation: 503

Replace

var numOfVisibleRows = $(this + 'tr:visible').length;

with

var numOfVisibleRows = $(this).find('tr:visible').length;

Upvotes: 1

Calvin Nunes
Calvin Nunes

Reputation: 6516

Take a look if this helps you.
Use the table that in this case is the context (this) to find it's visible tr childrens.

But I don't know if you want to check only tr from tbody or from thead too... (tell me and I edit my answer if needed)

Note that for the example I created two tables, but one doesn't have any visible tr, so it is hidden;

$(".report-table").each(function () {
      var numOfVisibleRows = $(this).find('tr:visible').length;
      if (numOfVisibleRows == 0)
          $(this).hide();
      else
          $(this).show();
});
table{
  border: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Table 1
<table class="report-table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Weather Report</td>
            <td>This report lists weather data.</td>
        </tr>
    </tbody>
</table>
<br>
Table 2 (will be hidden)
<table class="report-table">
    <thead>   
        <tr style="display:none">
            <th>Name</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>  
        <tr style="display:none">
            <td>Weather Report</td>
            <td>This report lists weather data.</td>
        </tr>
    </tbody>
</table>

Upvotes: 1

Omolewa Stephen
Omolewa Stephen

Reputation: 421

Are you hiding the entire table if no row or a particular row in the table?

Upvotes: 0

Related Questions