views:

36

answers:

0

Hi,

I am looking for an efficient way to expand/collapse hierarchical table rows using jQuery. The problem is, that the expand and collapse functionality differs.

  • Initially, only rows with class level_0 are show, all other rows are hidden.
  • expand should only show the next level, so clicking on row id=10 should only make rows with id=11 and id=14 visible.
  • collapse on the other hand, should collapse all consecutive rows with a deeper level than the current one. For example, clicking collapse on row id=10 should hide rows with ids 11, 12, 13, 14, if they are visible.

The table data looks as follows:

<table id="mytable">
    <tr class="level_0" id="10">...</td>
    <tr class="level_1 parent_10" id="11">...</td>
    <tr class="level_2 parent_11" id="12">...</td>
    <tr class="level_2 parent_11" id="13">...</td>
    <tr class="level_1 parent_10" id="14">...</td>
    <tr class="level_0" id="15">...</td>
</table>

My non-working solution:

$('#mytable tr').live('click', function() {
  var toggleClass = 'parent_' + $(this).attr('id');
  $(this).nextAll('tr').each(function() {
    if ($(this).is('.'+toggleClass)) {
      $(this).toggleClass("showme");
    }
  });
});

The problem is, that it only collapses the next level rows. Visible and deeper level rows beneath the clicked row are still shown.


Can anyone give me some hints on how I could do this in an efficient way? The HTML code can be adjusted if needed.

Thanks for any hints.