JQuery click-function for each link does not work

advertisements

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


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/