JSFiddle - React, Tailwind, and code Playground
HTML
<div class="selectallinput">
<label for="select-all">Select All</label>
<input type="checkbox" id="select-all">
</div>
<br>
<br>
<div class="inputs">
<br>
<label for="select-1">Select 1</label>
<input type="checkbox" id="select-1" checked>
<br>
<label for="select-2">Select 2</label>
<input type="checkbox" id="select-2" checked>
<br>
<label for="select-3">Select 3</label>
<input type="checkbox" id="select-3" checked>
<br>
<label for="select-4">Select 4</label>
<input type="checkbox" id="select-4" checked>
<br>
<label for="select-5">Select 5</label>
<input type="checkbox" id="select-5" checked>
</div>
JavaScript
function selectAll(wrapperAll, wrapperInputs) {
var selectAll = wrapperAll.find('input');
var allInputs = wrapperInputs.find('input');
console.log('Checked inputs = ' + allInputs.filter(':not(:checked)').length);
function checkitems(allInputs){
//If all items checked
if (allInputs.filter(':not(:checked)').length === 0) {
console.log('Function: checkItems: All items checked');
selectAll.attr('checked', true);
} else {
console.log('Function: checkItems: Else all items checked');
selectAll.attr('checked', false);
}
}
checkitems(allInputs);
allInputs.on('change', function(){checkitems(allInputs)});
selectAll.on('change', function () {
if (this.checked) {
console.log('This checkbox is checked');
wrapperInputs.find(':checkbox').attr('checked', true);
} else {
console.log('This checkbox is NOT checked');
wrapperInputs.find(':checkbox').attr('checked', false);
}
});
}
$(function () {
var wrapperAll = $('.selectallinput');
var wrapperInputs = $('.inputs');
selectAll(wrapperAll, wrapperInputs);
});