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>hong@test.com</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 속성