This question is a further development of this question:
jQuery simple checkbox to hide and show divs (product filtering) which was answered excellently by ManseUK
ManseUK’s solution enabled product filtering by a single category, specifically genre but for my current project I need to sort by 2 categories: colour and size. By modifying ManseUK’s solution I nearly have it working but it fails when I have two filters selected – in this example selecting ‘cyan’ and ‘xl’ should only show the xl cyan but instead it shows both cyans instead of just the xl cyan. The code I’m using is as follows:
HTML:
<input type="checkbox" id="cyan" value="cyan" /> Cyan<br />
<input type="checkbox" id="magenta" value="magenta" /> Magenta<br />
<input type="checkbox" id="black" value="black" /> Black<br />
<input type="checkbox" id="xl" value="xl" /> XL<br />
<!--------------------->
<div class="products">
<div class="productItem" data-price="250" data-category="cyan">
Cyan Ink
<div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="150" data-category="magenta">
Magenta Ink
<div class="productItemPrice"><span>£150</span></div>
</div>
<div class="productItem" data-price="250" data-category="black">
Black Ink <div class="productItemPrice"><span>£250</span></div>
</div>
<div class="productItem" data-price="241" data-category="cyan" data-size="xl">
XL Cyan Ink
<div class="productItemPrice"><span>£241</span></div>
</div>
</div>
<!--------------------->
CSS:
.productItem{float:left;padding:5px;margin:5px;border:1px solid #eaeaea}
body{font-family:verdana}
JS:
$('input[type="checkbox"]').click(function() {
if ($('input[type="checkbox"]:checked').length > 0) {
$('.products >div').hide();
$('input[type="checkbox"]:checked').each(function() {
$('.products >div[data-category=' + this.id + ']').show();
$('.products >div[data-size=' + this.id + ']').show();
});
} else {
$('.products >div').show();
}
});
I can see that the js is performing a logical OR on which divs to show – how can I make this an AND?
Made some changes to the code ..
Cached the variables.
You are looping over all the checkboxes and assigning the id’s to
it. You need to Query the size separately as it’s a different
entity..
I am looping only the checkboxes that is not size .. All colors
Then checking is Size is also check for each color…
FULL CODE
Check Fiddle