Amila
Amila

Reputation: 3816

jQuery Selector to Select Sections of a Table

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.

Upvotes: 1

Views: 112

Answers (2)

Felix Kling
Felix Kling

Reputation: 816840

nextUntil [docs] is your friend:

$('.evenPack, .oddPack').click(function() {
    var mod = this.className.indexOf('even') > -1 ? 'odd' : 'even';
    $(this).nextUntil('.' + mod + 'Pack').slideToggle();
});

If there are other rows in between .evenPack and .oddPack, you can filter the .*SubPack elements by passing a second argument to nextUntil:

$(this).nextUntil('.' + mod + 'Pack', '.' + (mod === 'even' ? 'odd' : 'even') + 'SubPack').slideToggle();

If .evenPack and .oddPack rows are always alternating, you could also do:

var $elements = $('.evenPack, .oddPack')
$elements.click(function() {
    $(this).nextUntil($elements.get($elements.index(this) + 1)).slideToggle();
});

This works since the elements are selected in the order they appear in the document. So instead of searching for the next element with class evenPack or oddPack, it just takes the next element in the selected set.

DEMO (note that .slideToggle does not seem to work properly with table rows (they don't slide))

Upvotes: 1

Starx
Starx

Reputation: 79031

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

Upvotes: 0

Related Questions