Jump to content

[SOLVED] Number of rows in a table


mwl707

Recommended Posts

Hi, The code below draws a 4x4 table using php. after that I use JS to get the number of rows in the table. The problem is I know there are only four rows but the 'r' value is 8. Can anyone tell me whats going wrong please ? Also I would like to get the total of columns can anyone give me a clue . Thanks

 

<script>

function check() {

 

var tab = document.getElementById('mytable');

var r = tab.rows.length

alert ®

}

</script>

 

</head>

<body>

 

  <?php

echo "<table id='mytable' border ='1' >" ;

for ($row = 1; $row<5; $row ++) {

echo "<tr>" ;

for ($col=1; $col<5; $col++) {

 

echo "<td  >$col $row" ;

echo "</td>" ;

}

echo "<tr>" ;

} // for

 

?>

 

  <label>

    <input type="button" id="button" value="Run JS "  onclick="check()"/>

  </label>

Link to comment
https://forums.phpfreaks.com/topic/178660-solved-number-of-rows-in-a-table/
Share on other sites

The following works for me:

 

<html>
   <head>
      <title>Table row count</title>
   </head>

   <body>
      <table id="myTable">
         <?php
            for($row = 0; $row < 4; ++$row)
            {
               echo "<tr>";

               for($col = 0; $col < 4; ++$col)
               {
                  echo "<td>$row-$col</td>";
               }

               echo "</tr>";
            }
         ?>
      </table>

      <button id="myButton">Click to count rows</button>

   </body>

   <script type="text/javascript">
      var oButton = document.getElementById('myButton');
      var oTable = document.getElementById('myTable');
      var numRows = oTable.getElementsByTagName('tr').length;

      oButton.onclick = function() {
         alert("Number of table rows: " + numRows);
      }
   </script>

</head>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.