Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle variable number of table rows

I have a table where clicking a link should show 'subrows' that belong to the data in the row clicked.

Since the subrows number may vary from 0 to n I think I should calculate the number of subrows by the .val method, is this right? So the value should be the number of invisble rows with class name 'affiliated' until the next tr without a class name. How can I do this? I made some attempts but I'm pretty new to jQuery.

I thought something like this to calculate the number of tr.affiliated:

 var affiliatednumber = $(this).find("tr.affiliated").val().stop();

DEMO

like image 281
user1901096 Avatar asked Dec 19 '12 15:12

user1901096


2 Answers

If you put a class on each parent tr you can use nextUntil() like this:

<tbody>
    <tr class="parent">
        <td>John</td>
        <td>HR Admin</td>
        <td>10/10/1980</td>
        <td>Yes</td>
        <td><a class="showaffiliated" href="#">Yes</a></td>
    </tr>
    <tr class="affiliated">
        <td colspan="2">Amanda</td>
        <td colspan="3">20/20/1985</td>
    </tr>
    <tr class="affiliated">
        <td colspan="2">Louis</td>
        <td colspan="3">20/10/2010</td>
    </tr>
</tbody>
$("tr.affiliated").hide();

$("a.showaffiliated").click(function() {
    var $affiliated = $(this).closest(".parent").nextUntil(".parent");
    $affiliated.toggle();
    var affiliatednumber = $affiliated.length;
});

Example fiddle

like image 136
Rory McCrossan Avatar answered Nov 09 '22 03:11

Rory McCrossan


http://jsfiddle.net/6t6QT/2/

Your use of .val and .stop don't make sense, and you are not using an input but an a. I used .nextUntil since the rows will be grouped together; just find the closest parent row of the a (this is the "master" row) and use .nextUntil to find its affiliated rows -- next until the other master row. It would also help if the master rows had their own class.

like image 35
Explosion Pills Avatar answered Nov 09 '22 01:11

Explosion Pills