fredag 6. februar 2009

How to hide rows in html tables, easily and correctly

I came into this problem a few days ago, and tried to search Google for "JavaScript hide table rows", what came up was abysmal, to say the least. Many iterated entire DOM trees using class names for each row to toggle. Some used regexp in class/id names. The solution came to me when thinking "isn't there something called row groups". A swift visit to w3c and it was done in 2 minutes!

The nitty-gritty:

This requires prototype, but is easily adjusted for any "ExplandorCollapse" JavaScript function.


Give table tags with ids for each group, then hide/show that id. It so simple you wish you had thought about it yourself!

[code]

<table>
<tbody>
<tr>
<th colspan="3" onmousedown="$('group1').toggle();">Group 1</th>

</tr>
</tbody>
<tbody id="group1">
<tr><td>row1 col1 </td><td>row1 col2 </td><td>row1 col2 </td></tr>

<tr><td>row 2 col1 </td><td>row 2 col2 </td><td>row 2 col3 </td></tr>
</tbody>
<tbody>

<tr><th onmousedown="$('group2').toggle();">Group 2</th></tr>
</tbody>
<tbody id="group2">
<tr><td>col1 </td><td>col2 </td><td>row 1 col3 </td></tr>

<tr><td>row 2 col1 </td><td>row 2 col2 </td><td>row 2 col3 </td></tr>
</tbody>
</table>

[/code]


check it out here:
http://thefivepillars.org/hideshow.html