Reputation: 29
I want to hide the rows with data under the row with header and button until next the row with header and button. clicking one of the +/- button hides/expands all the rows with data content. http://jsfiddle.net/9ekhuj1q/ Please find the code below-
<table border="0">
<tr>
<th>Data1</th>
<th>Data2</th>
</tr>
<tr class="header expand">
<td ><button class="url-button">
<span class="sign"></span>
</button></td>
<td>Header </td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr class="header expand">
<td ><button class="url-button">
<span class="sign"></span>
</button></td>
<td>Header </td>
</tr>
<tr>
<td>date</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
</table>
styling
table, tr, td, th
{
border: 1px solid black;
border-collapse:collapse;
}
tr.header
{
cursor:pointer;
}
.header .sign:after{
content:"+";
display:inline-block;
}
.header.expand .sign:after{
content:"-";
}
Click function-
$('.url-button').click(function(){
$('.header').toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});
Upvotes: 1
Views: 722
Reputation: 6165
Another similar way to do the job is to use event.target
:
$('.url-button').click(function(event){
$(event.target)
.closest('tr')
.toggleClass('expand')
.nextUntil('tr.header')
.slideToggle(100);
});
There are arguments for either one, but I prefer to use event.target
over this
, because it makes the object that this
refers to immediately obvious. In any case, your original code is selecting all elements with a .header
class, which as Emiel points out is the source of your problem.
Also, closest
and parents
have the same behavior in this case. (If you are interested in how they differ, have a look at this.)
Upvotes: 1
Reputation: 20944
Currently you are selecting all elements with the header
class whenever you click one of the buttons with $('.header')
. But you'll want to select the element with the header class that is a grandparent of the button you've just clicked.
Use the this
keyword to refer to the element you are listening on with the click()
event listener. That element will be the button that you've clicked on. From there you want to select the element with the header
class that is a parent of the button using .parent('.header')
. Now you've selected the correct element and not all the elements with the class.
$('.url-button').click(function() {
$(this)
.parents('.header')
.toggleClass('expand')
.nextUntil('tr.header')
.slideToggle(100);
});
Upvotes: 2