Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to find the next table row

Tags:

jquery

Using jQuery, how do you bind a click event to a table cell (below, class="expand") that will change the image src (which is in the clicked cell - original will be plus.gif, alternating with minus.gif) and hide/show the row immediately below it based on whether that row has a class of hide. (show it if it has a class of "hide" and hide if it does not have a class of "hide"). I am flexible with changing ids and classes in the markup.

Thanks

Table rows

<tr>
  <td class="expand"><img src="plus.gif"/></td>
  <td>Data1</td><td>Data2</td><td>Data3</td>
</tr>
<tr class="show hide">
  <td> </td>
  <td>Data4</td><td>Data5</td><td>Data6</td>
</tr>
like image 698
Jay Corbett Avatar asked Sep 23 '08 19:09

Jay Corbett


3 Answers

You don't need the show and hide tags:

$(document).ready(function(){   
    $('.expand').click(function() {
        if( $(this).hasClass('hidden') )
            $('img', this).attr("src", "plus.jpg");
        else 
            $('img', this).attr("src", "minus.jpg");

        $(this).toggleClass('hidden');
        $(this).parent().next().toggle();
    });
});

edit: Okay, I added the code for changing the image. That's just one way to do it. I added a class to the expand attribute as a tag when the row that follows is hidden and removed it when the row was shown.

like image 125
neuroguy123 Avatar answered Oct 13 '22 00:10

neuroguy123


Nobody has any love for the ternary operator? :) I understand readability considerations, but for some reason it clicks for me to write it as:

$(document).ready( function () {
    $(".expand").click(function() {
            $("img",this).attr("src", 
                 $("img",this)
                    .attr("src")=="minus.gif" ? "plus.gif" : "minus.gif"
            );
            $(this).parent().next().toggle();
    });
});

...and has the benefit of no extraneous classes.

like image 20
Pseudo Masochist Avatar answered Oct 12 '22 23:10

Pseudo Masochist


I had to solve this problem recently, but mine involved some nested tables, so I needed a more specific, safer version of javascript. My situation was a little different because I had contents of a td and wanted to toggle the next TR, but the concept remains the same.

$(document).ready(function() {
    $('.expandButton').click(function() {
        $(this).closest('tr').next('tr.expandable').fadeToggle();
    });
});

Closest grabs the nearest TR, in this case the first parent. You could add a CSS class on there if you want to get extremely specific. Then I specify to grab the next TR with a class of expandable, the target for this button. Then I just fadeToggle() it to toggle whether it is displayed or not. Specifying the selectors really helps narrow down what it will handle.

like image 22
PCasagrande Avatar answered Oct 12 '22 22:10

PCasagrande