I am trying to show/hide the next two rows of a table using jquery. The code below currently shows the tr with class – quest_image, but not class quest_text.
<table id="my_table">
<tr>
<td><img alt="Show/Hide" src="img.gif" class="ShowHide"></td>
<td>text 1</td>
</tr>
<tr class="quest_image">
<td colspan="2">hidden text 1</td>
</tr>
<tr class="quest_text">
<td colspan="2">hidden text 3</td>
</tr>
<tr>
<td><img alt="Show/Hide" src="img.gif" class="ShowHide"></td>
<td>text 2</td>
</tr>
<tr class="quest_image">
<td colspan="2">hidden text 4</td>
</tr>
<tr class="quest_text">
<td colspan="2">hidden text 2</td>
</tr>
</table>
<script type="text/javascript" src="../jquery/jquery/jquery-1.7.2.js"></script>
<script type="text/javascript">
// bind click event ONCE to the table
// not to every .ShowHide
$('#my_table').click(function(event){
// find where the click originated from
var trigger = event.target;
// if it has a class of "ShowHide"
// THEN toggle the next row
if(trigger.className == 'ShowHide')
{
// toggle away
$(trigger).closest('tr').next('.quest_text').toggle();
$(trigger).closest('tr').next('.quest_image').toggle();
}
});
</script>
Demo: http://jsfiddle.net/7TzJL/
Why does one toggle work, but not the other?
next()returns the immediate next element if the selector matches. It doesn’t select the closest element with matching selector. You need to usenextAll()and limit it to the first match.Also, jQuery 1.7 has
.on()so you can drop the convoluted class check and bind the event to the classes directly. Don’t forget to wrap everything in a document.ready event.Demo: http://jsfiddle.net/MaPaX/