I have multiple tables that are randomly generated. I only want the first row of each table displayed with the rest of the rows hidden. When I click on the visible row for a table I want the rest of its rows/contents to show/hide. How would I accomplish this using Jquery?
+1
A:
You should write some functions like this:
function AttachEvent(tableId)
{
$("#" + tableId + " tbody tr:first-child").click(ToggleRows);
}
function ToggleRows(e)
{
// get src table of e
// you can find code for this on SO or quirksmode.org (or basically anywhere)
$(src).find("tr").hide();
$(src).find("tr:first-child").show();
}
If you call AttachEvent with the id of the table when it is generated, it will bind the event to the first row.
These functions assume that the table is generated with all the rows except row[0] set to display:none.
I haven't tested this, but the theory should work. You may need to change some things like which event to bind, and whether to use the tr or the tds for showing/hiding.
Joel Potter
2009-04-08 13:44:36
+1
A:
To hide all the rows but the first:
$("table tbody tr:not(:first-child)").hide();
To make them visible when you click on the first row:
$("table tbody tr:first-child").click(function() {
$(this).siblings().show();
});
Alternatively you may want to organise your tables slightly differently (if possible):
<style type="text/css">
table tbody tr { display: none; }
</style>
<script type="text/javascript">
$(function() {
$("table thead tr").click(function() {
$("tbody tr", $(this).parents("table")[0]).show();
});
});
</script>
<table>
<thead>
<tr> ... first row is in thead not tbody ... </tr>
</thead>
<tbody>
<tr> ... row1 .. </tr>
<tr> ... row2 .. </tr>
<tr> ... row3 .. </tr>
</tbody>
</table>
There are lots of ways to skin this particular cat.
cletus
2009-04-08 14:30:31