Search code examples
javascriptphpgetelementbyid

Javascript function for a php loop


I have this situation:

<script type="text/javascript">
function myFunction() {
    var x = document.getElementById("commentDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

and the php code

<?php
echo "<table><tr  onclick='myFunction()'><td>Row A1</td></tr>"; //A1 row from my table
echo "<tr><td><div id='commentDIV' style='display:none'> Row B1</div></td></tr></table>"; // the B1 row show after click on the A1
?>

Everything works fine, when I click on the first row, the second appearance.

How can I use/modify my javascript function in this situation?

<?php
    $x=0;
    while($x<10){
        echo "<table><tr  onclick='myFunction()'><td>Row A$x</td></tr>"; //Ax row from my table
        echo "<tr><td><div id='commentDIV' style='display:none'> Row B$x</div></td></tr></table>"; // the Bx row must show after click on the Ax
        $x++;
    }
?>

Please help and save my day! Many thanks!


Solution

  • id attribute should be unique at the document, try to change the duplicate ones by common classes like :

    <?php
        $x=0;
        while($x<10){
            echo "<table><tr  onclick='myFunction(this)'><td>Row A$x</td></tr>"; //Ax row from my table
            echo "<tr><td><div class='commentDIV' style='display:none'> Row B$x</div></td></tr></table>"; // the Bx row must show after click on the Ax
            $x++;
        }
    ?>
    

    NOTE: You should pass the 'this' object as an argument to your function.

    Then in your js, you could use the passed argument to search for the related div using the class name self.nextElementSibling.querySelector(".commentDIV") and finally toggle the display like :

    function myFunction(self) {
      var related_div = self.nextElementSibling.querySelector(".commentDIV");
    
      related_div.style.display = (related_div.style.display === 'none') ? 'block' : 'none'
    }
    <table border=1>
      <tr onclick='myFunction(this)'>
        <td>Row A1</td>
      </tr>
      <tr>
        <td>
          <div class='commentDIV' style='display:none'> Row B1</div>
        </td>
      </tr>
    
      <tr onclick='myFunction(this)'>
        <td>Row A2</td>
      </tr>
      <tr>
        <td>
          <div class='commentDIV' style='display:none'> Row B2</div>
        </td>
      </tr>
    </table>