Seascape
Seascape

Reputation: 31

Trying to use jQuery to show/hide multiple lists independently

I have a web page where I am trying to hide extra bits of information by default. These extra bits take the form of lists of items that I want users to be able to show or hide by clicking a JavaScript link.

Initially, I used this code: http://jsfiddle.net/4Yk39/2/

 jQuery(document).ready(function() {
   jQuery('.bhlink').click(function(){
     jQuery('ul.billhistory').slideToggle();
   });
 });

... and it works just fine, except that clicking any of the JavaScript links on the page causes all the lists to appear or disappear, which is not what I want. I want only the list right below the JavaScript link to slide out when clicked. In other words, I need the lists to appear or disappear independently.

The code I'm working with now (derived from the answer to another StackOverflow question) is here: http://jsfiddle.net/smZct/

$(document).ready(function () {
$(".billhistory").slideUp();
$(".bhlink").click(function() {
    var billhistory = $(this).closest("p").find(".billhistory");
        var txt = billhistory.is(':visible') ? 'Click to view' : 'Click to hide';
        $(this).text(txt);
        billhistory.stop(true, true).slideToggle("slow");
    });
});

As far as I can tell, everything is set up properly, but when I click the link to show a list, the link changes to say "hide", but lists do not actually appear.

What am I doing wrong?

Upvotes: 0

Views: 648

Answers (2)

mansur
mansur

Reputation: 258

you need to use next instead of find for the text block:

var billhistory = $(this).closest("p").next(".billhistory");

Upvotes: 1

adeneo
adeneo

Reputation: 318182

jQuery(document).ready(function($) {
    $('.bhlink').on('click', function () {
        $(this).text(function (i, txt) {
            return txt.indexOf('view') != -1 ? 'Click to hide' : 'Click to view';
        }).closest('p').next('.billhistory').slideToggle();
    });
});

FIDDLE

Upvotes: 2

Related Questions