ex html
<div>
<div class="allfruit">
<input type="checkbox" id="allfruit"><label for="allfruit">과일</label>
</div>
<div class="water frs">
<input type="checkbox" id="water"><label for="water">수박</label>
</div>
<div class="melon frs">
<input type="checkbox" id="melon"><label for="melon">참외</label>
</div>
<div class="apple frs">
<input type="checkbox" id="apple"><label for="apple">사과</label>
</div>
</div>
function AllFuc() {
const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
const checkbox = $('.frs > input[type="checkbox"]');
Allcheckboxs.change(function(){
if(this.checked){
checkbox.prop('checked',true)
checkbox.parent().addClass('on')
}else{
checkbox.prop('checked',false)
checkbox.parent().removeClass('on')
}
})
}
모두체크박스가 변화할때 checked 상태면 각 체크박스를 checked true 처리하고 on클래스추가한다. checked 상태가 아니면 checked false처리후 on 클래스를 제거한다.
function checkboxUpdate(){
const checkboxCount = $('.frs > input[type="checkbox"]').length;
const checkedboxCount = $('.frs > input[type="checkbox"]:checked').length;
const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
if(checkboxCount == checkedboxCount){
Allcheckboxs.prop('checked',true)
}else{
Allcheckboxs.prop('checked',false)
}
}
if 함수로 check가 되어있는 박스와 안되어있는박스의 갯수를 조사해
모두체크박스 부분이 true false 체크된다.
checkbox.change(function(){
if(this.checked){
$(this).parent().addClass('on')
}else{
$(this).parent().removeClass('on');
}
checkboxUpdate()
})
// 체크박스들의 체크상태를 조사해 전체선택 버튼의 체크상태를 갱신
function checkboxUpdate(){
const checkboxCount = $('.frs > input[type="checkbox"]').length;
const checkedboxCount = $('.frs > input[type="checkbox"]:checked').length;
const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
if(checkboxCount == checkedboxCount){
Allcheckboxs.prop('checked',true)
}else{
Allcheckboxs.prop('checked',false)
}
}
function AllFuc() {
const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
const checkbox = $('.frs > input[type="checkbox"]');
Allcheckboxs.change(function(){
if(this.checked){
checkbox.prop('checked',true)
checkbox.parent().addClass('on')
}else{
checkbox.prop('checked',false)
checkbox.parent().removeClass('on')
}
})
checkbox.change(function(){
if(this.checked){
$(this).parent().addClass('on')
}else{
$(this).parent().removeClass('on');
}
checkboxUpdate()
})
}
AllFuc();