자바스크립트로 체크박스 전체 선택 및 반전 구현하기

체크박스 전체 선택과 반전 기능 구현

웹 개발에서 체크박스의 전체 선택과 선택 반전 기능은 정말 자주 사용되는 기능 중 하나입니다. 이 튜토리얼에서는 자바스크립트를 사용하여 이러한 기능을 구현하는 방법을 단계별로 알아보겠습니다.

기능 구현步骤

  1. 전체 선택 구현
  2. 자식 체크박스와 부모 체크박스 상태 동기화
  3. 선택 반전 기능 구현

HTML 및 CSS 구조

<style>
    * {
        padding: 0;
        margin: 0;
    }

    .container {
        width: 320px;
        margin: 80px auto 0;
    }

    table {
        border-collapse: collapse;
        border: 1px solid #b0b0b0;
        width: 100%;
    }

    th, td {
        border: 1px solid #c8c8c8;
        color: #333;
        padding: 12px;
        text-align: left;
    }

    th {
        background-color: #007bff;
        color: white;
        font-weight: 600;
    }

    td {
        font-size: 14px;
    }

    tbody tr:nth-child(odd) {
        background-color: #f8f9fa;
    }

    tbody tr:hover {
        background-color: #e9ecef;
    }
</style>

<div class="container">
    <table>
        <thead>
            <tr>
                <th>
                    <input type="checkbox" id="masterCheckbox"/>
                </th>
                <th>제품명</th>
                <th>가격</th>
            </tr>
        </thead>
        <tbody id="productList">
            <tr>
                <td><input type="checkbox" class="item-checkbox"/></td>
                <td>갤럭시 S24</td>
                <td>1,200,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="item-checkbox"/></td>
                <td>아이폰 15 Pro</td>
                <td>1,550,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="item-checkbox"/></td>
                <td>맥북 에어 M3</td>
                <td>1,800,000</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="item-checkbox"/></td>
                <td>아이패드 프로</td>
                <td>1,400,000</td>
            </tr>
        </tbody>
    </table>
    <button type="button" id="invertBtn" style="margin-top: 15px;">선택 반전</button>
</div>

1. 전체 선택 기능 구현

먼저 부모 체크박스를 클릭했을 때 모든 자식 체크박스의 상태를 동기화하는 기능을 구현합니다.

// 부모 체크박스 요소 가져오기
const masterCheckbox = document.getElementById('masterCheckbox');

// 자식 체크박스 요소들 가져오기
const productList = document.getElementById('productList');
const itemCheckboxes = productList.querySelectorAll('.item-checkbox');

// 부모 체크박스 클릭 이벤트 등록
masterCheckbox.addEventListener('click', function() {
    // 모든 자식 체크박스의 상태를 부모 체크박스와 동일하게 설정
    itemCheckboxes.forEach(function(checkbox) {
        checkbox.checked = this.checked;
    });
});

2. 자식 체크박스 상태 변경 시 부모 체크박스 동기화

개별 자식 체크박스를 클릭했을 때, 모든 자식 체크박스가 선택되어 있으면 부모 체크박스를 자동으로 선택하고, 하나라도 선택되지 않았으면 부모 체크박스의 선택을 해제합니다.

// 자식 체크박스 상태 변경 감지 함수
function synchronizeMasterCheckbox() {
    let allSelected = true;
    
    itemCheckboxes.forEach(function(checkbox) {
        if (!checkbox.checked) {
            allSelected = false;
        }
    });
    
    masterCheckbox.checked = allSelected;
}

// 각 자식 체크박스에 클릭 이벤트 등록
itemCheckboxes.forEach(function(checkbox) {
    checkbox.addEventListener('click', synchronizeMasterCheckbox);
});

3. 선택 반전 기능 구현

반전 버튼을 클릭하면 모든 자식 체크박스의 선택 상태를 반전시키고, 그에 맞춰 부모 체크박스 상태도 업데이트합니다.

// 선택 반전 버튼 요소 가져오기
const invertBtn = document.getElementById('invertBtn');

// 반전 기능 수행 함수
function toggleAllSelections() {
    // 모든 자식 체크박스의 선택 상태 반전
    itemCheckboxes.forEach(function(checkbox) {
        checkbox.checked = !checkbox.checked;
    });
    
    // 부모 체크박스 상태 동기화
    synchronizeMasterCheckbox();
}

// 반전 버튼에 클릭 이벤트 등록
invertBtn.addEventListener('click', toggleAllSelections);

전체 코드 통합

위에서 구현한 모든 기능을 하나의 스크립트로整合하면 다음과 같습니다.

// DOM 요소 참조
const masterCheckbox = document.getElementById('masterCheckbox');
const productList = document.getElementById('productList');
const itemCheckboxes = productList.querySelectorAll('.item-checkbox');
const invertBtn = document.getElementById('invertBtn');

// 부모 체크박스 상태 동기화 로직
function updateMasterState() {
    const allSelected = Array.from(itemCheckboxes).every(checkbox => checkbox.checked);
    masterCheckbox.checked = allSelected;
}

// 전체 선택 기능
masterCheckbox.addEventListener('click', function() {
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
    });
});

// 자식 체크박스 individually monitoring
itemCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('click', updateMasterState);
});

// 선택 반전 기능
invertBtn.addEventListener('click', function() {
    itemCheckboxes.forEach(checkbox => {
        checkbox.checked = !checkbox.checked;
    });
    updateMasterState();
});

구현 포인트 정리

  • 부모 체크박스의 checked 속성을 사용하여 모든 자식 체크박스 상태 제어
  • every() 메서드를 활용하여 모든 체크박스 선택 상태 확인
  • 이벤트 위임을 통해 효율적인 이벤트 처리
  • 상태 변경 시마다 부모-자식 체크박스 상태 동기화 유지

태그: JavaScript checkbox DOM web-api frontend

7월 23일 23:37에 게시됨