简体   繁体   中英

Count rows in table and if greater than 0 show table

I have a table that gets results from my SQL database and shows them on my html page. I want the table to be hidden until the rows are greater than 0.

I have this to count the number of rows:

var oRows = document.getElementById('tableID').getElementsByTagName('tr');
    var iRowCount = oRows.length;

And this is my table

<table border="1" id="tableID">
  <tr>
      <th>Results</th>
  </tr>
  <tr>
      <td><%response.Write(checker) %></td>
  </tr>
</table>

Checker is the string from my database.

I want to be able to only show my table when the row count is greater than 0. Anybody know how to do this?

If you want to manage this on the frontend side, and since you don't seem to be using jQuery:

if (iRowCount == 0) {
    document.getElementById("tableID").style.display = 'none';
}

You ca try this out

var table = document.getElementById('tableID');
if (table.rows.length > 0)
   table.style.visibility = "visible";
else
   table.style.visibility = "hidden";

OR

  var table = document.getElementById('tableID');
    if (table.rows.length > 0)
       table.style.display = 'none';
    else
       table.style.display = 'table';

For example

 var oTable    = document.getElementById('tableID');
 var oRows     = oTable.getElementsByTagName('tr');
 var iRowCount = oRows.length;

 // If the length be zero
 if(iRowCount == 0) {
      // Hide the table
      oTable.style.display = 'none';
 } else {
      // show the table
      oTable.style.display = 'initial';
 }

Why initial ? It's browsers default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM