Good day professionals. How to hide a table by clicking on the "table header"? Now I do it through Javascript, and I insert it into the tag of a row of the table

echo '<table class="table_dep2">'; $result = array(); for ($i = 0; $i < $entries['count']; $i++){array_push($result,$entries[$i]["department"][0]);} $result=array_unique($result); sort($result); echo '<tr><th colspan="4">Отделы</th></tr>'; for ($j = 0; $j < (count($result)/4)+1; $j++) { echo '<tr id="hidethis">'; echo '<td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-3].'">'.$result[$j*4-3].'</a></td>'; echo '<td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-2].'">'.$result[$j*4-2].'</a></td>'; echo '<td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-1].'">'.$result[$j*4-1].'</a></td>'; echo '<td><a href="http://localhost/index2.php?dep_link='.$result[$j*4].'">'.$result[$j*4].'</a></td>'; echo '</tr>'; } echo '</table>'; 

javascript code:

 <script> function toggle() { if( document.getElementById("hidethis").style.display=='none' ){ document.getElementById("hidethis").style.display = ''; }else{ document.getElementById("hidethis").style.display = 'none'; } } </script> 

And the link link:

 <a href="#null" onclick="toggle()">Показать ОТДЕЛЫ:</a> 

QUESTION: As soon as I generate rows of tables with php code, I can’t hide them anymore. I do not understand why, because the tr tag always remains, and it is one for all td . Can there be any other way how to do this? THX

  • java! = javascript - ermak0ff
  • you have getElementById function when hiding returns only the first line, but not all. If you need to hide a few, work with the class, not the identifier. (if the problem is this, of course, otherwise I understood little) - teran
  • oh it accidentally fell .. - Oleg Zolotarenko
  • Attach an example of layout in question - DaemonHK

1 answer 1

Most likely, you call a function earlier than you define it.

Either place js above the markup, or use this option (set the id of your link and click directly in js, not in the markup):

 var link = document.getElementById('link'); link.onclick = function toggle() { if( document.getElementById("hidethis").style.display=='none' ){ document.getElementById("hidethis").style.display = ''; }else{ document.getElementById("hidethis").style.display = 'none'; } } 
 <table border="1"> <tr id="hidethis"> <td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-3].'">'.$result[$j*4-3].'</a></td> <td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-2].'">'.$result[$j*4-2].'</a></td> <td><a href="http://localhost/index2.php?dep_link='.$result[$j*4-1].'">'.$result[$j*4-1].'</a></td> <td><a href="http://localhost/index2.php?dep_link='.$result[$j*4].'">'.$result[$j*4].'</a></td> </tr> </table> <br /> <a href="#null" id="link">Показать ОТДЕЛЫ:</a>