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.
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
- How can I have "Show all" be checked on page load?
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 >1</div>
<div >1,2</div>
<div >1,3</div>
<div >2</div>
<div >2,3</div>
<div >3</div>
<div >3,2</div>
<div >1</div>
<div >2</div>
<div >3</div>
<div >2</div>
<div >1</div>
</div>
CodePudding user response:
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>