flolaloop flolaloop - 1 month ago 24
jQuery Question

Show all divs when all checkboxes are unchecked

I am try to do a quick and simple filter function on my website. Where users can check and uncheck the checkboxes to filter what they want to see.

Currently i'm using this script:

$(".filter-obj :checkbox").click(function() {
$(".obj").hide();
$(".filter-obj:checkbox:checked").each(function() {
$("." + $(this).val()).show();
});
});


This is my HTML:

<ul class="filter-obj">
<li>
<div class="checkbox">
<input class="filter-search" id="filter-obja" value="a" type="checkbox">
<label for="filter-obja"> Object A</label>
</div>
</li>
<li>
<div class="checkbox">
<input class="filter-search" id="filter-objb" value="b" type="checkbox">
<label for="filter-objb"> Object B</label>
</div>
</li>
</ul>


<!-- my objects -->
<div class="obj a">Object A</div>
<div class="obj a">Object A</div>
<div class="obj b">Object B</div>
<div class="obj b">Object B</div>


It works perfectly well at showing only whats checked and hiding whats unchecked. However, I also want it to show all the divs again when everything is unchecked. Help?

Answer

You can get the length of checked boxes and if it returns 0(false) then show()

var check = $(".filter-obj :checkbox:checked").length;

if(!check) return $(".obj").show();

Edit Using return will stop the rest of the code from running.

$(".filter-obj :checkbox").click(function() {
    var check = $(".filter-obj :checkbox:checked").length;
    if(!check) return $(".obj").show();

    $(".obj").hide();
    $(".filter-obj:checkbox:checked").each(function() {
       $("." + $(this).val()).show();
    });

});