Caelum
Caelum

Reputation: 448

JQuery click-function for each link does not work

I am currently working on a "collapse all"-button for Bootstrap 3 collapsible plugin. It seems to work fine, but only if I have got only one single collapsible on my page. When I add another one, my method will still just work in the first link item.

Here ist my JS:

$(function () {
    $("#toggle-all").click(function (e) {
        e.preventDefault();

        var $hidden = $(this).parent().data("hidden");

        if ($hidden == "false") {
            $(this).parent().find(".collapse.in").each(function () {
                $(this).collapse("hide");
            });
            $(this).parent().data("hidden", "true");
        } else {
            $(this).parent().find(".collapse").not(".in").each(function () {
                $(this).collapse("show");
            });
            $(this).parent().data("hidden", "false");
        }

        $(this).find("i").toggleClass("fa-plus fa-minus");
    });
});

And here a fiddle to try: http://jsfiddle.net/rMdLZ/

Any ideas why it does not work as expected?

Thanks, Julian

Upvotes: 1

Views: 320

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

Don't use ids. Use classes and I think you should do fine.

Why?

Because the ids have to be unique through out the frame.

$('#someId') will always return you the same element, but $('.someClass') will return you all elements with someClass class

I've changed $("#toggle-all").click to $(".toggle-all").click and added the toggle-all class the the collapse all buttons. And it works fine.

Demo

Upvotes: 4

mawburn
mawburn

Reputation: 2336

You are using 2 id's. Id's must be unique elements on each document.

See this SE question for reference: Two HTML elements with same id attribute: How bad is it really?

Change it to Classes:

$(function () {
  $(".toggle-all").click(function (e) {
    e.preventDefault();

    var $hidden = $(this).parent().data("hidden");

    if ($hidden == "false") {
        $(this).parent().find(".collapse.in").each(function () {
            $(this).collapse("hide");
        });
        $(this).parent().data("hidden", "true");
    } else {
        $(this).parent().find(".collapse").not(".in").each(function () {
            $(this).collapse("show");
        });
        $(this).parent().data("hidden", "false");
    }

    $(this).find("i").toggleClass("fa-plus fa-minus");
  });
});

http://jsfiddle.net/vP4e9/1/

Upvotes: 4

Related Questions