I have requrement to collapse/expand nested tables using jquery (Parent,child,grand child etc).
- Initially all parents will be collapsed.
- When click a parents its child only exapnd.
Please look at my jsfiddle
http://jsfiddle.net/vivekcek/36SRa/
<table border="1">
<thead>
<tr>
<td></td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
</tr>
</thead>
<tbody>
<tr>
<td><a href="#">[+]</a></td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td colspan="5">
<table border="1">
<tbody>
<tr class="parent">
<td><a href="#">[+]</a></td>
<td>Data</td>
</tr>
<tr class="child">
<td colspan="2">
<table border="1">
<tbody>
<tr>
<td><a href="#">[+]</a></td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr class="child">
<td colspan="4">
<table border="1">
<thead>
<tr>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="parent">
<td><a href="#">[+]</a></td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr class="child">
<td colspan="4">
<table border="1">
<thead>
<tr>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="parent">
<td><a href="#">[+]</a></td>
<td>Data</td>
</tr>
<tr class="child">
<td colspan="2">
<table border="1">
<tbody>
<tr>
<td>[+]</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td colspan="4">
<table border="1">
<thead>
<tr>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
<td>Header</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
I am using jquery like this
<script type="text/javascript">
$(document).ready(function () {
function getChildren($row) {
var children = [];
while ($row.next().hasClass('child')) {
children.push($row.next());
$row = $row.next();
}
return children;
}
$('.parent').on('click', function () {
var children = getChildren($(this));
$.each(children, function () {
$(this).toggle();
})
});
$.each($('.parent'), function () {
var children = getChildren($(this));
$.each(children, function () {
$(this).toggle();
})
});
})