Reputation: 668
I have three html tables on a webpage that are generated using a tornado framework. When a user clicks on a table, I would like all rows of this table to toggle hidden / shown, except for the first and last rows of this table. I am trying to use jQuery's each and toggle to accomplish this.
Fiddle here: https://jsfiddle.net/kauk975e/
$(".hidesomerows").each(function() {
$(function(){
$(function() {
$('table').click(function() {
console.log('click registered');
$(this).parent().find("tr").not(":last").not(":first").toggle();
console.log('why you no work?');
});
});
});
});
When I click on the first table, it prints my two debug message to the console once for each table displayed, but doesn't hide the rows. Nothing happens when I click on the second or third table. What am I missing??
Upvotes: 0
Views: 32
Reputation: 133453
You don't need to use .parent()
, as event handler is attached with TABLE
element. the current element context this
will refer it. So directly use .find()
to target the TR
s
$('table.hidesomerows').click(function() {
$(this).find("tr").not(":last").not(":first").toggle();
});
$('table.hidesomerows').click(function() {
$(this).find("tr").not(":last").not(":first").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table hidesomerows">
<tbody>
<tr>
<th>foo</th>
<th>bar</th>
<th>x</th>
<th>y</th>
</tr>
<tr>
<td> alpha </td>
<td> alpha </td>
<td>-20.0</td>
<td>20.0</td>
</tr>
<tr>
<td>beta</td>
<td>beta</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>gamma</td>
<td>gamma</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>total</td>
<td> </td>
<td> 0 </td>
<td> -20 </td>
</tr>
</tbody>
</table>
<br>
<table class="table hidesomerows">
<tbody>
<tr>
<th>foo</th>
<th>bar</th>
<th>x</th>
<th>y</th>
</tr>
<tr>
<td> alpha </td>
<td> alpha </td>
<td>-20.0</td>
<td>20.0</td>
</tr>
<tr>
<td>beta</td>
<td>beta</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>gamma</td>
<td>gamma</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>total</td>
<td> </td>
<td> 0 </td>
<td> -20 </td>
</tr>
</tbody>
</table>
<br>
<table class="table hidesomerows">
<tbody>
<tr>
<th>foo</th>
<th>bar</th>
<th>x</th>
<th>y</th>
</tr>
<tr>
<td> alpha </td>
<td> alpha </td>
<td>-20.0</td>
<td>20.0</td>
</tr>
<tr>
<td>beta</td>
<td>beta</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>gamma</td>
<td>gamma</td>
<td>124.390625</td>
<td>-20.0</td>
</tr>
<tr>
<td>total</td>
<td> </td>
<td> 0 </td>
<td> -20 </td>
</tr>
</tbody>
</table>
Upvotes: 2