0

I have a javascript code to count records in html table, but it counts all and I need to count not empty only: If I click the button it shows 5 rows, but I need to make count equal to 4. Need java-script code to skip empty rows.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script>
     $(document).ready(function(){
     $("button").click(function(){
         var rowCount = $("#myTable tr").length;
         alert(rowCount); // Outputs: 4
     });
     });
  </script>
</head>
<body>
  <table id="myTable" border="1" width="140">
     <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
     </tr>
     <tr>
            <th></th>
            <th></th>
            <th></th>
     </tr>
     <tr>
            <td>1</td>
            <td>John</td>
            <td>25</td>
     </tr>
     <tr>
            <th></th>
            <th></th>
            <th></th>
     </tr>
     <tr>
            <td>2</td>
            <td>Peter</td>
            <td>18</td>
     </tr>
     <tr>
            <td>3</td>
            <td>Harry</td>
            <td>14</td>
     </tr>
  </table>
   <br>
  <button type="button">Get Number of Rows</button>
</body>
</html>
arkady
  • 1
  • 1

1 Answers1

0

Seems what u need is just filter out the empty rows that is getting saved in rowcount. May be this code can help.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script>
     $(document).ready(function(){
     $("button").click(function(){
         var rowCount = $("#myTable tr");
         //\t\t indecates that the row is empty
         var filteredRowCount = $.grep(rowCount, n => n.innerText!="\t\t" );
         alert(filteredRowCount.length); // Outputs: 4
     });
     });
  </script>
</head>
<body>
  <table id="myTable" border="1" width="140">
     <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
     </tr>
     <tr>
            <th></th>
            <th></th>
            <th></th>
     </tr>
     <tr>
            <td>1</td>
            <td>John</td>
            <td>25</td>
     </tr>
     <tr>
            <th></th>
            <th></th>
            <th></th>
     </tr>
     <tr>
            <td>2</td>
            <td>Peter</td>
            <td>18</td>
     </tr>
     <tr>
            <td>3</td>
            <td>Harry</td>
            <td>14</td>
     </tr>
  </table>
   <br>
  <button type="button">Get Number of Rows</button>
</body>
</html>

Refer this link to find more ways to filter the array

Omkar Pattanaik
  • 380
  • 3
  • 8