본문 바로가기
JAVA SCRIPT

전체 체크박스, 자식 체크박스 다루기(자바스크립트, JQuery)

by hhana 2023. 8. 1.
//자식 체크박스 클릭 이벤트
function chkClicked() {
	//체크박스 전체 갯수
    const allCount = document.querySelectorAll(".chk").length;
    //체크된 체크박스 갯수
    const checkedCount = $('input[name=trgt]:checked').length;
    //체크박스 전체 갯수와 체크된 체크박스 갯수가 같으면 전체 체크박스 체크
    if (allCount == checkedCount) {
    	document.getElementById('allCheckBox').checked = true;
    }
    //체크박스 전체 갯수와 체크된 체크박스 갯수가 같지 않으면 전체 체크박스 체크 해제
    else {
    	document.getElementById('allCheckBox').checked = false;
    }
}

//체크박스 전체 선택 클릭 이벤트
function allChecked(trgt) {
	//전체 체크박스 버튼
    const checkbox = document.getElementById('allCheckBox');
    //전체 체크박스 버튼 체크 여부
    const isChecked = checkbox.checked;
    
    //전체 체크박스 제외한 모든 체크박스
    if (isChecked) {
    	chkAllChecked()
    } else {
    	chkAllUnChecked()
    }
}

//체크박스 전체 체크
function chkAllChecked() {
	document.querySelectorAll(".chk").forEach(function(v, i) {
    	v.checked = true;
    })
}

//체크박스 전체 체크 해제
function chkAllUnChecked() {
	document.querySelectorAll(".chk").forEach(function(v, i) {
    	v.checked = false;
    })
}

//대상이 선택되지 않았을때
if ($('input[name=trgt]:checked').length == 0) {
	alert("대상이 선택되지 않았습니다.");
    return;
}

댓글