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
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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.