Václav Zeman
Václav Zeman

Reputation: 616

jQuery - show only one item of the same class after click

I've got 2 classes - .item and .item-description. Item is always visible but item-description is not. It should be visible right after the user clicks on the button and on the next click it should hide again.

Here's my JSFiddle.

The jQuery function looks like this and somehow it is not working :-)

$(function() {
  $("table .item td:last-child").click(function() {
    $(this).parent().closest(".item-description").show();
  });
});

Upvotes: 1

Views: 1394

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You have used wrong selector. you need to either use .next() or .siblings() instead of .closest() :

$(this).parent().next().show();

using .toggle:

$(this).parent().next().toggle();

Working Demo

using toggleClass:

$(this).parent().next().toggleClass('item-description');

Demo

Upvotes: 3

Simcha Khabinsky
Simcha Khabinsky

Reputation: 2039

Here is my solution:

$("table > tbody > tr.item").click(function() {    
    $(this).next("tr").toggle();
});

JSFIDDLE: http://jsfiddle.net/sZp3C/7/

Upvotes: 1

Robert Messerle
Robert Messerle

Reputation: 3032

Here is how I would tackle this problem:

$(function () {
    $("table .item td:last-child").click(function () {
        //-- Store a reference to the description element
        var $next = $(this).parent().next('.item-description');
        //-- Toggle the description, causing it to either hide or show.
        $next.toggle();
        //-- hide all sibling descriptions
        $next.siblings('.item-description').hide();
    });
});

Updated JSFiddle: http://jsfiddle.net/sZp3C/8/

Upvotes: 1

Related Questions