Filtering with checkboxes using jQuery

I think the two most straightforward approaches would be on click of any of the filter checkboxes either:

  1. Hide all <div> elements, then loop through the checkboxes and for each checked one .show() the <div> elements with the associated category.

  2. Loop through all checkboxes to make a list of the classes to be shown, then loop through the <div> elements, checking each one to see if it has one of those classes and .hide() or .show() as appropriate.

Is there some general selector you can use to get all the <div> elements? Do they have a particular container element, like how all the checkboxes are descendents of "#filters"?

// Solution 1

$("#filters :checkbox").click(function() {
   $("div").hide();
   $("#filters :checkbox:checked").each(function() {
       $("." + $(this).val()).show();
   });
});

Demo: http://jsfiddle.net/6wYzw/41/

// Solution 2

$("#filters :checkbox").click(function() {

   var re = new RegExp($("#filters :checkbox:checked").map(function() {
                          return this.value;
                       }).get().join("|") );
   $("div").each(function() {
      var $this = $(this);
      $this[re.source!="" && re.test($this.attr("class")) ? "show" : "hide"]();
   });
});

Demo: http://jsfiddle.net/6wYzw/42/

I guess the first way is shorter, and easier to maintain...


I wanted to add jquery animation to showing and hiding. The above solutions were not allowing this (first hiding everything, then showing) or were cumbersome with regular expressions. My solution, based on the above, is as follows:

var showselector = $('input:checkbox').map(function(){ 
        return this.checked ? '.' + this.id : null; 
    }).get().join(','); 
var hideselector = (showselector) ? ':not(' + showselector + ')' : '*';

$("div").filter(showselector).slideDown(1500);
$("div").filter(hideselector).slideUp(1500);