user611105
user611105

Reputation:

Hiding table rows using jquery, simplifying function

Currently I'm trying to hide some table rows and have a toggle link that shows and hides them when the link is clicked. Now currently I have it working but I was wondering if there's an easier way to make the function totally generic instead of copy and pasting a bunch of the same code with just different class names (or IDs). From what I understand of JS/Jquery (this is the first time I've done JS/JQuery, I'm usually a back-end developer) it looks like using a table probably isn't the wisest idea but I'm modifying original code. I'll rewrite it if I have to to use something other than tables but I just need some direction if it's not possible

<table>
    <tr>
        <th>Some stuff</th>
        <a href="#" class="hide link1">Show/Hide</a>
    </tr>
    <tr class="show hide row1">
        <th>Random data</th>
    </tr>
        <tr>
        <th>Some stuff2</th>
        <a href="#" class="hide link2">Show/Hide</a>
    </tr>
    <tr class="show hide row2">
        <th>Random data2</th>
    </tr>
        <tr>
        <th>Some stuff3</th>
        <a href="#" class="hide link3">Show/Hide</a>
    </tr>
    <tr class="show hide row3">
        <th>Random data3</th>
</table>

<script>
    $(".hide link1").click(function(){
        $(".show hide row 1").toggle(400)
    });
    $(".show hide row 2").hide()
    $(".hide link2").click(function(){
        $(".show hide row 2").toggle(400)
    });
    $(".show hide row 2").hide()
    $(".hide link3").click(function(){
        $(".show hide row3").toggle(400)
    });
    $(".show hide row3").hide()
</script>

Upvotes: 2

Views: 2231

Answers (1)

Ram
Ram

Reputation: 144659

You can traverse the DOM:

$(function() {
    $("table a.hide").click(function(e){
        e.preventDefault();
        $(this).closest('tr').next('tr.show').toggle(400);
    });
});

Note that jQuery selectors work like CSS selectors so your selector should be:

$(".show.hide.row2").hide();

Instead of:

$(".show hide row 2").hide();

Which selects and hides pseudo element 2:

<tr class='show'>
   <hide>
       <row>
          <2>Come-on!</2>
       </row>
   </hide>
</tr>

Upvotes: 2

Related Questions