Products

Products
Viewing By Entry / Main
July 31, 2007

Hide dynamically generated table rows

Here's one that almost had me coding till midnight until I found a quick simple solution.

If your trying to use javascript DHTML to hide and show multiple generated dynamic table rows with one link/button you may find yourself pulling your hair out. Surrounding the tr's with a div won't work. And giving the tr itself an id and doing it that way won't work because there will be more than one. Then if you try to dynamically name the id's and loop through them; nightmare!!

Tbody to the rescue. I hate tbody's. I never use them and despise when word html includes them. But this is the one time I can think of a good use for it. Surround your dynamically created tr's with one of these, give it an id, and use that to hide and show all the rows at one time.

code example:

script language="javascript" type="text/javascript">
function display(elementid){
   if(document.getElementById(elementid).style.display == "none"){
      document.getElementById(elementid).style.display = "inline";
   }else{
      document.getElementById(elementid).style.display = "none";
   }
}
</script>

<table>
<tr><td>Rows of data: (<a href="#" onclick="display('hidden');">Click to view rows</a>)</td></tr>
   <tbody id="hidden" style="display:none">
      <!---dynamically generated rows of data--->
      <tr><td>row 1</td></tr>
      <tr><td>row 2</td></tr>
      <tr><td>row 3</td></tr>
      <tr><td>row 4</td></tr>
   </tbody>
<tr><td>End of data rows</td></tr>
</table>

Comments

this was helpful...

thanks


This, of course, is the incorrect usage for tbody. :|


It also doesnt work in firefox :(


i find this very useful. what happens if i go several levels deep? when i click, it will not collapse all the children nodes, but only the specific node. does that make sense? could you modify it to collapse all children nodes below the one clicked?


there is no reason to use tbody here. you can just insert the id and style directly into the tr rows


Your blog caters all the information a professional developer needs. It not only makes the mark with its comprehensive as well as informative posts but also deeply discusses topics add more to it. Appreciative effort keep it up.



Copyright © 2005-2006 Clint Willard. All rights reserved.
Aura skin for Clint Willard's BlogCFC inspired by Brooks Bilson's Bolg.
All trademarks property of their owners.