DescX
DescX

Reputation: 334

Hide multiple table rows by class

I've got a pretty large table of companies, these companies can have a daughter, these are listed underneath them. I want to be able to toggle each 'section' of daughters per company.

If a company has daughters, I added a <span class="image"> to each <td> which displays a image. If you click on the image, the rows of the daughters will be toggled.

The layout looks like this:

 <tr>
     <td><span class="image"></span>
     <td>Company</td>
 </tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr><td>Company</td></tr>
 <tr><td>Company</td></tr>
 <tr><td>Company</td></tr>
 <tr>
     <td><span class="image"></span>
     <td>Company</td>
 </tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>
 <tr class="company_daughter"><td>!data</td></tr>

 etc

So far I came up with this:

$('.image').click(function(){ 
    var closest = $(this).closest('tr')
    $('tr.company_daughter').each(function(){
            closest.hide();
        }
    );
});

Each company should only display her own daughters

However I seem not to be able to get the 'section' problem right.

Upvotes: 3

Views: 2286

Answers (3)

Onur Topal
Onur Topal

Reputation: 3061

The below code should what you want;

$('.image').click(function(){ 
    // get the clicked company row
    var closest = $(this).closest('tr');
    //give main company class "company"
    closest.nextUntil("tr.company").each(function(){
            //Every this means tr.company_daughter
            $(this).toggle();
        }
    );
});

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

I'd suggest, though currently untested:

$('.image').click(function(){
    $(this).closest('tr').nextUntil('tr:has(".image")').toggle();
});

References:

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

I believe this will work, it will hide all company_daughter after that .image has been clicked:

$(".image").click(function() {
    $(this).closest("tr").nextUntil("tr:not(.company_daughter)").toggle();
});

Demo: http://jsfiddle.net/Rj5Ac/2/

Upvotes: 1

Related Questions