Web Spring 전정프
체크박스 checkbox 전체선택 해제 스크립트 javascript
zeuz
2020. 11. 17. 14:06
반응형
체크박스 하나라도 해제 시 전체 체크박스 해제 스크립트입니다.
$(document).ready(function(){
$("input[type=checkbox]").on("click",function(){ //체크박스가 클릭될 때
if($(this).attr("id") == "chkAll"){ //전체 체크인 경우
if($(this).is(":checked")){ //전체 체크가 체크되었을 경우
$("input[type=checkbox]").each(function(){ //체크박스 전체 검사
if($(this).attr("id") == "chkAll"){
return true; //전체 체크 일 경우 continue
}
$(this).prop("checked",true); //전체 체크가 아닐 경우 체크
})
}else{ //전체 체크가 체크 해제되었을 경우
$("input[type=checkbox]").each(function(){ //체크박스 전체 검사
if($(this).attr("id") == "chkAll"){
return true; //전체 체크 일 경우 continue
}
$(this).prop("checked",false);
//전체 체크가 아닐 경우 체크 해제
})
}
}else{ //전체 체크가 아닌 경우
var chkCnt = 0; //체크된 체크박스 수
var allCnt = 0; //전체 체크박스 수
$("input[type=checkbox]").each(function(){ //체크박스 전체 검사
if($(this).attr("id") == "chkAll"){
return true; //전체 체크 일 경우 continue
}
allCnt++; //전체 체크가 아닐 경우 전체 체크박스 수 증가
if($(this).is(":checked")){
//현재 검사 중인 체크박스가 체크되어 있을 경우
chkCnt++; //전체 체크박스 수 증가
}
});
if(chkCnt == allCnt ){
//전체 체크박스 수와 체크된 체크박스 수가 같을경우
$("#chkAll").prop("checked",true); //전체 체크박스 체크
}else{
$("#chkAll").prop("checked",false); //전체 체크박스 체크 해제
}
}
});
});
<input type="checkbox" id="chkAll"/> <!--전체 체크 체크박스에 id값 설정-->
반응형