Giang Nguyen
Giang Nguyen

Reputation: 485

Jquery toggle() wanted table row only

I have a table generated from a php loop so that Toggled row has the same class. When i clicked to toggle to show details of one records, it toggles to all other records.

This is a bit confusing. So i tried to create a jsfiddle here.

<table border=1px>
<tr>
    <td>MR A</td><td><a class='showit' href='#'>2 records</a></td>
</tr>
<tr class='details'>
    <td colspan='2'>record 1....</td>
</tr>
<tr class='details'>
    <td colspan='2'>record 2....</td>
</tr>
 <tr>
    <td>MR B</td><td><a class='showit' href='#'>1 records</a></td>
</tr>
<tr class='details'>
    <td colspan='2'>record 1....</td>
</tr>

</table>
<script>
$(document).ready(function(){
$(".details").hide();
$(".showit").click(function(){
    $(".details").toggle();
});
});
</script>

The problem is that When i click to show records of mR A, it also show records of mR B. Is there any solution for this? Many thanks...

Upvotes: 1

Views: 188

Answers (1)

Stryner
Stryner

Reputation: 7318

You can capture the row that was clicked on and retrieve all subsequent rows that have the class details:

$(".showit").click(function(){
    $(this).closest("tr") // Retrieves the tr that was clicked
           .nextUntil(":not(.details)") // Gets all the following tr's that have the detail class
           .toggle();
});

Updated fiddle: http://jsfiddle.net/bxfw05s5/1/

Upvotes: 3

Related Questions