I have a list of checkboxes that I want to select and unselect.
The problem currently is that when I click All, all items in the list are added to an array called filter. However when I click All again, the list is repopulated with the items again. It is supposed to empty the filter array and uncheck all checkboxes.
How can I uncheck all the boxes if I select the All checkbox again?
The list consist of:
if(!empty($items)){ ?>
<input class="form-check-input select-item" data-item="All" type="checkbox" value="All" id="All">
<label class="form-check-label item-label" for="All">All </label>
<?php foreach ($items as $entry): ?>
<input class="form-check-input select-item" data-item="<?php echo $entry['short_name'];?>" type="checkbox" value="<?php echo $entry['short_name'];?>" id="<?php echo $entry['short_name'];?>">
<label class="form-check-label item-label" for="<?php echo $entry['short_name'];?>"><?php echo $entry['full_name'];?> </label>
<?php endforeach; ?>
<?php } ?>
This is the JavaScript I have at the moment:
$(".select-item").click(function(e){
var item = $(this).data('item');
if(item=="All") {
console.log($('#items input:checkbox').length);
if(filterAllChecked()) {
console.log("in");
$('#items input:checkbox').prop('checked',"");
filter = [];
} else {
$('#items input:checkbox').prop('checked', 'checked');
var items = $("#items input:checkbox:checked").map(function(){
return $(this).val();
}).get();
filter = items;
console.log($('#items input:checkbox').filter(":checked").length);
}
} else {
var index = $.inArray(item,filter);
if(this.checked && index === -1) {
filter.push(item);
} else {
filter.splice(index,1);
}
}
console.log(filter);
});
This is the check to see if all items have been selected:
function filterAllChecked(){
var checkboxes = $("#items input:checkbox");
return checkboxes.length === checkboxes.filter(":checked").length;
}