简体   繁体   中英

Filtering divs by classes with checkboxes

I'm currently working on filtering a pile of divs with checkboxes.

<ul id="filters">
    <li>
        <table id="filters_opt" width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
        <td><input type="checkbox" checked value="Familien" id="filter-Familien" />
        <label for="filter-Familien">Familien/Kinder</label></td>

        <td><input type="checkbox" checked value="Jugend" id="filter-Jugend" />
        <label for="filter-Jugend">Jugend</label></td>

        <td><input type="checkbox" checked value="Senioren" id="filter-Senioren" />
        <label for="filter-Senioren">Senioren</label></td>

        <td><input type="checkbox" checked value="Musik" id="filter-Musik" />
        <label for="filter-Musik">Musik</label></td>
        <td rowspan="3" align="center" id="filter_anwenden_big"><input type="button" class="send_button" value="Filter anwenden"></td>
       <tr>
</table>   
    </li>
</ul>



$("#filters :checkbox:checked").each(function() {

   $("." + $(this).val()).show();

});

so far this is showing all divs with the classes selected by the checkboxes. But I can't seem to wrap my head around the following:

When I have these conditions: class A class B or a combination ie classes A + B + C

Shouldn't the results get smaller? It seems to always display all divs from class A, all divs from class B and all divs from class C. But I'd like to display results like only divs that contain class A + B. And not A and B seperately.

Any ideas my fellow coders?

JsFiddle! - Here's a working example. If I check on "Erwachsene" and "Flingern" it shouldn't show the "only Flingern" example nor the "Senioren - Flingern - Duesseltal" example.

What I'm trying to achieve is that the more checkboxes I activate, the more results will be narrowed down until only few are left.

With my current code it just shows too much results. Because it shows all divs with the class "Flingern" and all with the class "Erwachsene".

Hope this makes it clearer.

You can change your selector query like this :

    $(".send_button").click(function() {

      $(".filter").hide();

      var classes = ['.filter'];

      $("#filters :checkbox:checked").each(function() {
               classes.push($(this).val());
           });

      $(classes.join('.')).show();

      return false;
   });

Updated Fiddle : https://jsfiddle.net/d621ageL/1/

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