I have many articles which have multiple categories. I have a checkbox for every category. When a checkbox is checked the articles with this category should be shown, otherwise should be hidden.
So far so good.
When I check category 1, but not category 2 all posts should be shown which have category 1. If they have category 2 too they should be shown anyway.
<input type="checkbox" value="cat1" id="checkbox1" checked />
<input type="checkbox" value="cat2" id="checkbox2" checked />
<input type="checkbox" value="cat3" id="checkbox3" checked />
<input type="checkbox" value="cat4" id="checkbox4" checked />
I use jQuery to show and hide the posts
if ($('#checkbox1').is(':checked')) {
$("article.category1").show();
} else {
$("article.category1").hide();
}
if ($('#checkbox2').is(':checked')) {
$("article.category2").show();
} else {
$("article.category2").hide();
}
if ($('#checkbox3').is(':checked')) {
$("article.category3").show();
} else {
$("article.category3").hide();
}
if ($('#checkbox4').is(':checked')) {
$("article.category4").show();
} else {
$("article.category4").hide();
}
I created a js fiddle for this
http://jsfiddle.net/oliverspies/t8qHT/1/
If you uncheck all, but check the first checkbox, no entries are shown – but all entries with the class cat1 should be shown – even if they have another category which is unchecked.
How can I do this without writing tens of IF statements?
Fixed code
You can create a selector based on the input’s value.
See it here.
Previous code