March 24, 2012

jQuery Selector to Select Sections of a Table

Question by Amila

I have the following table in my page

<table>
<tr class="evenPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="oddPack">
</tr>
<tr class="oddSubPack">
</tr>
<tr class="oddSubPack">
</tr>
<tr class="oddSubPack">
</tr>
<tr class="oddSubPack">
</tr>
<tr class="evenPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
<tr class="evenSubPack">
</tr>
</table>

The evenPack rows and oddPack rows are clickable. When the user clicks on one of them, I want the immediate SubPack rows to toggleSlide().

for example, if the user clicks on the first row, which is a evenPack. Then only the four evenSubPack rows that are immediately after the first evenPack should toggleSlide. It shouldn’t toggleSlide() the evenSubPack rows that are at the bottom of the table.

I can’t think of the selector to do this.

Answer by Starx

You can use nextUntil() for this:

$("tr").click(function() {
    var active =  $(this).attr("class").indexOf('even') > -1 ? 'odd' : 'even';
    //find if the clike in even, and find out out the next stop point will be
    $(this).nextUntil('.' + active + 'Pack').slideToggle();
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!