I’m attempting to make a table that has header rows that can be collapsed and expanded by using jQuery. Here is the entirety of my code thus far:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
$("tr#cat1.header").click(function () {
$("tr#cat1.child").each(function() {
$(this).slideToggle("fast");
});
});
});
</script>
</head>
<body>
<table>
<tr id="cat1" class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr id="cat1" class="child">
<td>data1</td>
<td>data2</td>
</tr>
<tr id="cat1" class="child">
<td>data3</td>
<td>data4</td>
</tr>
<tr id="cat2" class="header">
<td>Cat1</td>
<td>Row</td>
</tr>
<tr id="cat2" class="child">
<td>data1</td>
<td>data2</td>
</tr>
</table>
</body>
</html>
If I am correct, the jQuery part in English reads like: “When a row that has an ID of ‘cat1’ and a class of ‘header’ is clicked, find all rows that have an id of ‘cat1’ and a class of ‘child’, and for each one, slideToggle.”
Yet when I run it and click on a header row, nothing happens. Any insight?
EDIT: Added a second category to the HTML table. Sorry, I should have been more specific. I want to be able to click on a header row for a particular category, and have only those child rows collapse, not all child rows on the page. In such a manner the table behaves like an “accordian”, and the rows are grouped together by category.
This will cause the click to only affect the rows in the table containing the header you clicked on, which means you can change it to work with a css class instead of duplicating the id.
Basically
thisis the header that is clicked, we wrap that in a jQuery object and callparent()(which returns the table), and then specify it as the context for the new query.Your page now looks something like this: