제이쿼리 체크박스 전체선택 on&off / JQuery Check All on&off
개발시 테이블 태그에서 자주 사용되는 체크박스의 전체선택/전체해제 코드입니다.
(체크박스 항목중, disabled옵션을 반영하여 작성된 코드입니다.)
관련 함수는 총 두가지로 이루어져있습니다.
1. 체크박스 그룹 일괄 on/off 함수
2. 체크박스 그룹내 항목 개별 선택시, 그룹 전체항목이 체크되면 일괄체크박스에 체크시키는 함수
- 테이블 태그 설정 html 부분 입니다.
<table class="table border">
<thead>
<tr>
<th><input type="checkbox" id="checkAll" /></th>
<th>번호</th>
<th>아이디</th>
<th>이름</th>
<th>생년월일</th>
<th>성별</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="checkGroup" /></td>
<td>1</td>
<td>hong</td>
<td>홍길동</td>
<td>2021-04-02</td>
<td>남</td>
</tr>
....
<tr>
<td><input type="checkbox" class="checkGroup"/></td>
<td>5</td>
<td>gan</td>
<td>간달프</td>
<td>2021-04-02</td>
<td>남</td>
</tr>
</tbody>
</table>
전체선택 on/off 체크박스의 id는 "checkAll"이고, 해당될 요소들의 클래스명은 "checkGroup"으로 구성하였습니다.
- 체크박스("checkAll")를 선택/해제 시, 그룹("checkGroup") 전체에 대하여 일괄적으로 선택/해제 시키는 함수입니다.
/* 체크박스 전체선택,해제 적용*/
$(document).on('click','#checkAll',function(){
$('.checkGroup:not(:disabled)').not(this).prop('checked', this.checked);
});
그룹내의 체크박스 옵션중 "disabled" 설정되어있는 항목은 제외합니다.
- 그룹("checkGroup")요소의 개별 선택/해제 시, 전체항목이 체크되어있다면 체크박스("checkAll")를 선택시킵니다.
/* 체크박스 개별요소 반영 */
$(document).on('click','.checkGroup',function(){
if($('.checkGroup:not(:disabled)').length == $('.checkGroup:checked').length){
$('#checkAll').prop('checked',true);
}else{
$('#checkAll').prop('checked',false);
}
});
상단의 미리보기gif 의 코드전문을 확인하고싶으시다면, 아래 첨부파일을 확인해주세요.
'IT > Javascript' 카테고리의 다른 글
JavaScript 숫자형 input설정 / 총점 자동계산 / 설문지 작성 (0) | 2021.07.04 |
---|---|
JavaScript 문자열대체 / 공백제거 / replace / replace All (0) | 2021.04.18 |
제이쿼리 이미지 미리보기 / 이미지 툴팁 / JQuery Image Preview (0) | 2021.01.18 |
textarea 글자수 제한 / 바이트(Byte) 제한 (0) | 2021.01.16 |