简体   繁体   中英

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?

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();
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM