tags:

views:

40

answers:

3

I have a table like this:

<table id="tbl">
     <tr><th>My Table</th></tr>
     <tr><td><div class="arrow"></div></td></tr>
     <tr><td>The second row</td></tr>
</table>

I want to show / hide the tr after arrow. I have written this script:

$(document).ready(function () {
    $("#tbl tr:odd").addClass("odd");
    $("#tbl tr:even").addClass("even");
    $("#tbl tr:not(.odd)").hide();
    $("#tbl tr:first-child").show();
    $('.arrow').click(function () {
        $(this).next("tr").toggle();
        $(this).toggleClass("up");
    });
});

but this cant show or hide tr. How can I solve this. Thanks

+1  A: 

Use parents("tr:first") to walk up the chain and select the parent tr of the div then it should work. It should be noted that there are some selector optimizations you might want to make for your other calls/setup.

$(document).ready(function() {
    $("#tbl tr:odd").addClass("odd");
    $("#tbl tr:even").addClass("even");
    $("#tbl tr:not(.odd)").hide();
    $("#tbl tr:first-child").show();
    $('.arrow').click(function(){
      $(this).parents("tr:first").next("tr").toggle();
      $(this).toggleClass("up");
    });
});
Quintin Robinson
+2  A: 

if you put in a call to closest() before next(), you'll get the TR for the arrow, and then next() will select the row after that.

$(this).closest("tr").next().toggle();
dave thieben
+1  A: 

This'll do it, i stripped out your hiding and showing code cos it was making all the rows not display in the first place.

what you need to do is get the closes tr from your arrow div, then get the next one from that.

$(document).ready(function() {
    $("#tbl tr:odd").addClass("odd");
    $("#tbl tr:even").addClass("even");

    $('.arrow').click(function(){
        $(this).closest('tr').next("tr").toggle();
        $(this).toggleClass("up");
    });
});

jsfiddle: http://jsfiddle.net/SLc5d/

Patricia