I have a simple Isotope grid with checkbox inputs to sort the items in a grid. This works OK. The problem is the interaction between the "Show All" checkbox and the different category checkboxes.
When "Show All" is checked, I have to manually uncheck it to be able to check any category checkboxes. And when I uncheck all the categories, I'd like to have "Show all" check itself to indicate that all category items are being shown.
https://codepen.io/bluedogranch/pen/MWvdyNm
How can I have "Show All" uncheck itself when any one or all of the categories are checked?
How can I have "Show All" check itself when all of the categories are unchecked?
and
jQuery
var $container = $('#container').isotope({
itemSelector: '.product',
layoutMode: 'fitRows',
transitionDuration: '0.2s'
});
var $checkboxes = $('#filters input');
$checkboxes.change(function(){
var filters = [];
// get checked checkboxes values
$checkboxes.filter(':checked').each(function(){
filters.push( this.value );
});
filters = filters.join(', ');
$container.isotope({ filter: filters });
});
CSS
.product {
float: left;
width: 50px;
height: 50px;
border: 1px solid #000;
padding:10px;
text-align:center;
margin: 5px;
}
#container {
width:400px;
HTML
<div id="filters">
<label><input type="checkbox" value="*" id="all">Show all</a></li>
<label><input type="checkbox" value=".category1" id="category1">Category 1</label>
<label><input type="checkbox" value=".category2" id="category2">Category 2</label>
<label><input type="checkbox" value=".category3" id="category3">Category 3</label>
</div>
<div id="container">
<div class="product category1">1</div>
<div class="product category1 category2 ">1,2</div>
<div class="product category1 category3">1,3</div>
<div class="product category2">2</div>
<div class="product category2 category3">2,3</div>
<div class="product category3">3</div>
<div class="product category3 category2">3,2</div>
<div class="product category1">1</div>
<div class="product category2">2</div>
<div class="product category3">3</div>
<div class="product category2">2</div>
<div class="product category1">1</div>
</div>
About #1 and #2, just check during the event which target was changed. You can do this by accessing event.currentTarget
.
$checkboxes.change(function(event) {
After this, just add the logic:
let currentTarget = event.currentTarget;
// if all is selected, deselect others
if (currentTarget.id == "all")
$("#filters input:not(#all)").prop("checked", false);
else // remove the checked prop from all
$("#all").prop("checked",false);
// if none is checked anymore, check all
if (!$checkboxes.filter(":checked").length)
$("#all").prop("checked", true)
// your code
var filters ...
And about the 3rd one, just add the checked
property to the input field.
<label><input type="checkbox" value="*" checked id="all">Show all</label>