Learning JQuery 1.3 - Expanding and Collapsing
I have a dynamically created table and I’m using Learning JQuery 1.3 to toggle open and closed different sections of the table.
The table is as follows:
- <table id="topics" width=700>
<thead>
<tr>
<th>SUBJECT</th>
<th>SELECT</th>
</tr>
</thead>
<tbody>
<tr class="parent" id="1">
<th colspan="1"><strong>TOPIC 1</strong></th>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-1">
<td>SUB-TOPIC 1</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-1">
<td>SUB-TOPIC 2</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-1">
<td>SUB-TOPIC 3</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-1">
<td>SUB-TOPIC 4</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
</tbody>
<tbody>
<tr class="parent" id="2">
<th colspan="1"><strong>TOPIC 2</strong></th>
<td><input name="" type="checkbox" value="" /></td>
</tr>
</tbody>
<tbody>
<tr class="parent" id="3">
<th colspan="1"><strong>TOPIC 3</strong></th>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-3">
<td>SUB-TOPIC 1</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
<tr class="child-3">
<td>SUB-TOPIC 2</td>
<td><input name="" type="checkbox" value="" /></td>
</tr>
</tbody>
</table>
And the Javascript that runs the collapsing and expanding (came straight from Learning jQuery 1.3) is as follows:
- $(document).ready(function() {
var toggleMinus = '../images/icons/toggle_minus.png';
var togglePlus = '../images/icons/toggle_plus.png';
var $subHead = $('tbody th:first-child');
$subHead.prepend('<img src="' + toggleMinus + '"alt="collapse this section" />');
$('img', $subHead).addClass('clickable')
.click(function() {
var toggleSrc = $(this).attr('src');
if ( toggleSrc == toggleMinus ) {
$(this).attr('src', togglePlus)
.parents('tr').siblings().fadeOut('slow');
} else{
$(this).attr('src', toggleMinus)
.parents('tr').siblings().fadeIn('slow');
};
});
})
So far everything is working but I would like be able to open the table in the closed toggle state and allow the user to open it if they would like to and some of the topis do not have subtopics so I would also like to hide the toggle button if there are no subtopics. Could anyone point me in the right direction.
Thanks
Gareth Edwards