Reputation: 10686
I have this HTML:
<table class="itemsTable table table-striped table-condensed table-hover">
<thead>
<tr>
<th>#</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr class="collapse">
<td class="center">1</td>
<td>
<a href="locations?location_id=1">Title 1</a>
</td>
</tr>
<tr class="collapse">
<td class="center">2</td>
<td>
<a href="locations?location_id=2">Title 2</a>
</td>
</tr>
<tr class="collapse">
<td class="center">3</td>
<td>
<a href="locations?location_id=3">Title 3</a>
</td>
</tr>
</tbody>
</table>
<a href="#" class="collapseBtn">test</a>
And jQuery:
$('.collapseBtn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.itemsTable').find('.collapse');
$collapse.collapse('toggle');
});
I want rows show/hide behavior on link click. What is wrong?
Upvotes: 1
Views: 711
Reputation: 40038
As of 130918_1100PST the selected answer is not correct. Although the writer did correctly identify why the closest()
selector would not return any elements to collapse, this alone did not fix the OP's problem.
This selector will also work for selecting the elements to collapse:
$('.collapse').methodgoeshere();
but the elements won't expand/collapse -- it's not just a matter of the selector used.
The key to solving the problem, as user Chad identified in his jsFiddle below benjaminbenben's answer, is actually that the wrong method was used.
This did not work:
selector.collapse('toggle');
This did:
selector.toggle();
Therefore, the correct answer was:
$('.collapseBtn').on('click', function() {
$('.collapse').toggle();
});
Upvotes: 1
Reputation: 1228
$.closest will look up the dom tree for a matching element - the .itemsTable isn't a parent of .collapseBtn
- so $this.closest('.itemsTable')
won't match any elements.
So, Either put the .collapseBtn
within the table, or use $this.prev()
instead of $this.closest('.itemsTable')
.
You can test if there are matching elements by running $('.collapseBtn').closest('.itemsTable')
in the console
Upvotes: 2