Contents
see List작성일 2014. 09. 25.
jQuery 체크박스 전체 선택/해제 구현
jQuery로 체크박스 전체 선택 기능을 구현하는 방법입니다. 실무에서 자주 사용하는 패턴과 응용 예제를 다룹니다.
1. HTML 구조
<input type="checkbox" id="checkAll"> 전체 선택
<input type="checkbox" class="item" value="1"> 항목 1
<input type="checkbox" class="item" value="2"> 항목 2
<input type="checkbox" class="item" value="3"> 항목 3
2. 기본 전체 선택
// 전체 선택 체크박스 클릭 시
$("#checkAll").on("click", function() {
$(".item").prop("checked", $(this).prop("checked"));
});
// 개별 체크박스 클릭 시 전체 선택 상태 갱신
$(".item").on("click", function() {
var total = $(".item").length;
var checked = $(".item:checked").length;
$("#checkAll").prop("checked", total === checked);
});
3. change 이벤트 사용 (권장)
// 전체 선택
$("#checkAll").on("change", function() {
$(".item").prop("checked", this.checked);
});
// 개별 선택 시 전체 선택 동기화
$(".item").on("change", function() {
var allChecked = $(".item").length === $(".item:checked").length;
$("#checkAll").prop("checked", allChecked);
});
4. 테이블에서 사용
<table>
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>이름</th>
<th>이메일</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="item" data-id="1"></td>
<td>홍길동</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
// 테이블 전체 선택
$("#checkAll").on("change", function() {
$(this).closest("table").find("tbody .item").prop("checked", this.checked);
});
5. 선택된 항목 처리
// 선택된 값 배열로 가져오기
$("#deleteBtn").on("click", function() {
var selectedIds = $(".item:checked").map(function() {
return $(this).data("id");
}).get();
if (selectedIds.length === 0) {
alert("선택된 항목이 없습니다.");
return;
}
console.log("삭제할 ID:", selectedIds);
// AJAX 처리
});
6. 동적 체크박스 처리
// 이벤트 위임 (동적 추가된 요소 처리)
$(document).on("change", "#checkAll", function() {
$(".item").prop("checked", this.checked);
});
$(document).on("change", ".item", function() {
var allChecked = $(".item").length === $(".item:checked").length;
$("#checkAll").prop("checked", allChecked);
});
7. 선택 개수 표시
function updateCount() {
var total = $(".item").length;
var checked = $(".item:checked").length;
$("#countDisplay").text(checked + " / " + total + " 선택됨");
}
$(".item, #checkAll").on("change", updateCount);
8. 페이지 전환 시 선택 유지
// 선택 상태 저장
var selectedItems = [];
$(".item").on("change", function() {
var id = $(this).data("id");
if (this.checked) {
if (selectedItems.indexOf(id) === -1) {
selectedItems.push(id);
}
} else {
selectedItems = selectedItems.filter(function(item) {
return item !== id;
});
}
sessionStorage.setItem("selectedItems", JSON.stringify(selectedItems));
});
// 페이지 로드 시 복원
$(function() {
var saved = sessionStorage.getItem("selectedItems");
if (saved) {
selectedItems = JSON.parse(saved);
selectedItems.forEach(function(id) {
$(".item[data-id=" + id + "]").prop("checked", true);
});
}
});
attr vs prop 주의
| 메서드 | 용도 | 예시 |
|---|---|---|
| prop() | 현재 상태 (권장) | 체크 여부 변경 |
| attr() | HTML 속성 | 초기 checked 속성 |
javascript
| No | 작성일 | Title |
|---|---|---|
| 3384 | 2026. 08. 21. | Node.js API에서 요청 취소를 제대로 처리하는 방법: AbortSignal로 외부 작업 정리하기 |
| 3352 | 2026. 08. 13. | Node.js 응답이 간헐적으로 느릴 때: 이벤트 루프 지연 측정과 CPU 작업 분리 방법 |
| 3320 | 2026. 08. 04. | JavaScript fetch 요청을 안전하게 만드는 방법: timeout·재시도·오류 처리 실전 패턴 |
| 3288 | 2026. 07. 27. | Node.js 서버 무중단 배포를 위한 Graceful Shutdown 구현 가이드 |
| 3257 | 2026. 07. 19. | Node.js 대용량 파일 처리 가이드: 스트림과 backpressure로 메모리 사용량 제어하기 |
| 3232 | 2026. 07. 11. | Node.js 실무형 에러 처리: async/await에서 실패를 일관되게 분류하고 복구 속도 높이기 |
| 3174 | 2026. 07. 02. | Node.js 환경 변수 검증 가이드: process.env를 안전한 설정 객체로 바꾸기 |
| 3123 | 2026. 06. 24. | TypeScript 타입 좁히기 운영 가이드: unknown 입력을 안전한 도메인 객체로 바꾸기 |
| 3065 | 2026. 06. 16. | 브라우저 성능 병목 찾기: PerformanceObserver로 LCP·INP·긴 작업 로그 수집하기 |
| 2978 | 2026. 06. 08. | Node.js fetch 타임아웃과 재시도 설계: 외부 API 장애 전파 줄이기 |