0

I have a layout similar to this:

<tr>
    <td class="topCategoryRow"><a href="javascript:void(0);" class="catlink">Some Category</a></td>
</tr>
<tr>
    <td class="subCategoryRow">A sub category under Some Category</td>
</tr>
<tr>
    <td class="subCategoryRow">Another sub category under Some Category</td>
</tr>
<tr>
    <td class="topCategoryRow"><a href="javascript:void(0);" class="catLink">Another Category</a></td>
</tr>
<tr>
    <td class="subCategoryRow">A sub category under Another Category</td>
</tr>
<tr>
    <td class="subCategoryRow">Another sub category under Another Category</td>
</tr>

What I'm trying to do is attach a click handler on catLink classes. I want to be able to select the subCategoryRows under the topCategoryRows:

<script type="text/javascript">
    $(function() {
        $(".catLink").click(function() {
            $(".subCategoryRow").show(); // This selector is wrong
        });
    });
 </script>

The code I have selects ALL subCategoryRow's. I want to select only the ones under the category selected. Can someone help me build the correct selector?

1
  • Perhaps your classes would be better attached to the <tr>s and not the <td>s? Commented Nov 25, 2013 at 17:03

2 Answers 2

3

Try

$(function() {
    $(".catlink").click(function() {
       $(this).closest('tr').nextUntil("tr:has(.catlink)").find('.subCategoryRow').show();
    });
});

Demo: Fiddle

note: class names are case sensitive - you have used catlink and catLink

Sign up to request clarification or add additional context in comments.

2 Comments

This works, except for the last item though. Keep in mind that there will be no more "catlink" tags after the last one.
@icemanind you are using the class name as catLink for the second item that is the problem change it to catlink checkout the fiddle
0

Try this too.

$(function() {
    $(".catLink").click(function() {
        var xCurrentObj = $(this).closest('tr');
        $('.subCategoryRow').filter(function(){
            return ($(this).parent().index() > xCurrentObj.index());
        }).show();
    });
});

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.