sarah3585 sarah3585 - 6 months ago 62
jQuery Question

Checkbox filtering using Jquery

I'm using this code: http://jsfiddle.net/6wYzw/42/ to filter categories, however I need the functionality to be slightly different. If more than one filter is checked the item most contain both to be display.

Example:

Checking Category A and B would only display 'AB' not all instances of 'A' and 'B'

HTML:

<ul id="filters">
<li>
<input type="checkbox" value="categorya" id="filter-categorya" />
<label for="filter-categorya">Category A</label>
</li>
<li>
<input type="checkbox" value="categoryb" id="filter-categoryb" />
<label for="filter-categoryb">Category B</label>
</li>




<div class="item categorya categoryb">A, B</div>
<div class="item categorya">A</div>
<div class="item categorya">A</div>
<div class="item categorya">A</div>
<div class="item categoryb">B</div>
<div class="item categoryb">B</div>
<div class="item categoryb">B</div>


JS:

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

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

Answer

You don't need to use a regular expression for this. Instead you can join() the array you create with map() by a . to build a class selector which you can then use to directly show the required elements. Try this:

<ul id="filters">
    <li>
        <input type="checkbox" value="categorya" id="filter-categorya" />
        <label for="filter-categorya">Category A</label>
    </li>
    <li>
        <input type="checkbox" value="categoryb" id="filter-categoryb" />
        <label for="filter-categoryb">Category B</label>
    </li>
</ul>

<div class="category-container">
    <div class="categorya categoryb">A, B</div>
    <div class="categorya">A</div>
    <div class="categorya">A</div>
    <div class="categorya">A</div>
    <div class="categoryb">B</div>
    <div class="categoryb">B</div>
    <div class="categoryb">B</div>
</div>
$("#filters :checkbox").click(function() {
    var filter = '.' + $("#filters :checkbox:checked").map(function() {
        return this.value;
    }).get().join(".");

    $('.category-container div').hide();
    $(filter).show();
});

Updated fiddle