tags:

views:

733

answers:

3

Hi guys,

Currently got this JQuery code...

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { $(this).closest('.r3c').toggle(); return false; });
});

And here's my HTML:

<tr>
    <td class="show_r3c">click here</td>
</tr>
<tr class="r3c">
    <td>This is what I'd like to display</td>
</tr>

For some reason the closest() function isn't working, and it won't toggle the table row .r3c - I've tried using parent and other alternatives but can't get it working eitehr :(

Apologies for the silly question, and something similar to a problem I've had before... just wondering what the best solution is for this.

Thanks!

+1  A: 

perhaps this would work:

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { 
        $(this).parent().siblings(":first").toggle(); 
        return false; 
    });
});
stefita
That is perfect, thank you!! :)
Nick
+3  A: 

closest() finds the closest parent not the parents-siblings-children.

You want something like:

$(document).ready(function(){
    $(".r3c").hide();

    $('.show_r3c').click(function() { 
        $(this).closest('table').find("tr.r3c").toggle(); return false; 
    });
});
Damo
Since the question was 'Using the Jquery closest() function?' this is the best answer for sure. The other answers are mroe about how to traverse the DOM using jquery without using closest :)
Ryan
+1 Helped me out..thx!
Johan Leino
+2  A: 

Try with:

$('.show_r3c').click(function() {
  $(this).parent('tr').next('tr.r3c').toggle();
  return false;
});
CMS