user1872809
user1872809

Reputation: 85

jQuery hide parent div based on checkbox

I have the following code: http://jsfiddle.net/p9s0pdao/

$("#filters :checkbox").change(function() {
    $(".listing-details > div").hide();
    $("#filters :checkbox:checked").each(function() {
        $(".listing-details ." + $(this).val()).show();
    });
});

Instead of hiding the .listing-details css class, I need to hide the div which starts with .wpbdp-listing

How can I go about this?

Thanks.

Upvotes: 1

Views: 711

Answers (4)

George G
George G

Reputation: 7695

It's better to have things separated and clean: I mean we can have one function that does everything, thus we can call it anytime we wish. I mean calling it after DOM loads, and next when checkboxes change.

ToggleThings();

$("#filters :checkbox").change(function() {
    ToggleThings();
});

function ToggleThings()
{
    $(".wpbdp-listing").hide();
    $("#filters :checkbox:checked").each(function() {
        $('.' + $(this).val()).closest('.wpbdp-listing').show();
    });
}

http://jsfiddle.net/p9s0pdao/1/

Update (final solution):

ToggleThings();

$("#filters :checkbox").change(function() {
    ToggleThings();
});

function ToggleThings()
{
    var checkedboxes = $("#filters :checkbox:checked");

    if (checkedboxes.length > 0)
    {
        $(".wpbdp-listing:visible").hide();

        checkedboxes.each(function() {
            $('.' + $(this).val()).closest('.wpbdp-listing').show();
        });
    }
    else
    {
        $(".wpbdp-listing").show();
    }
}

http://jsfiddle.net/p9s0pdao/4/

Upvotes: 4

Norrj
Norrj

Reputation: 114

Try This code, Test it at JsFiddle

$(".wpbdp-listing").hide()
$("#filters :checkbox").change(function() {
        $(".listing-details ." + $(this).val()).parents('.wpbdp-listing').hide();
    $("#filters :checkbox:checked").each(function() {
        $(".listing-details ." + $(this).val()).parents('.wpbdp-listing').show();
    });
});

I added the " $(".wpbdp-listing").hide()" just to start it of so that the divs are hidden cuz the checkboxes are unchecked at first. you can also make it so the checkboxes are checked at first and then just remove that line.

Upvotes: 2

Dionys
Dionys

Reputation: 3113

To get the parent node no matter how deep up it is, use .closest() jquery method

$(".listing-details > div").closest('.wpbdp-listing').hide()

have a look at doc http://api.jquery.com/closest/

Upvotes: 3

Matthias
Matthias

Reputation: 637

You can get the parent element of an element in JQuery with .parent().

$(".listing-details").parent().hide();

Upvotes: 1

Related Questions