728x90

체크박스에 체크하고 삭제하는 글관리 구현 중 전체 체크박스를 체크하는 기능을 구현한다.

 


1. html 코드

                <table class="table caption-top table-bordered table-hover">
                    <caption>List</caption>
                    <thead>
                        <tr>
                            <th class="text-center" width="50" scope="col">
                                <input type="checkbox" onclick="selectAll(this)">
                            </th>
                            <th class="text-center" width="50" scope="col">No</th>
                            <th class="text-center" width="950" scope="col">제목</th>
                            <th class="text-center" width="200" scope="col">작성일</th>
                            <th class="text-center" width="180" scope="col">작성자</th>
                        </tr>
                    </thead>

                    <tbody>
                        <tr th:each="board : ${boardList}">
                            <td class="mt-5 text-center" scope="row">
                                <div class="checkbox">
                                    <input type="checkbox" name="boardIdList" th:value="${board.id}">
                                </div>
                            </td>
                            <td class="mt-5 text-center" scope="row" th:text="${board.id}">1</td>
                            <td><a th:text="${board.title}" th:href="@{/board/post(boardId=${board.id})}"
                                    style="text-decoration:none; color:black;">제목</a></td>
                            <td class="text-center" th:text="${#dates.format(board.createDate, 'yyyy/MM/dd HH:mm')}">작성일
                            </td>
                            <td class="text-center" th:text="${board.writer}">작성자</td>
                        </tr>
                    </tbody>
                </table>
  • 체크박스에 onclick 이벤트를 달아준다.

2. 스크립트 코드

    <script>
        function selectAll(selectAll) {
            var checkboxs = document.querySelectorAll(['input[type="checkbox"]'])

            checkboxs.forEach((checkbox) => {
                checkbox.checked = selectAll.checked
            })
        }
    </script>
  • document.querySelectorAll : 모든 체크박스 쿼리를 가져옴
  • this로 체크박스를 받았기 때문에 this체크박스가 체크되면 모든 체크박스가 체크되도록 코드 작성

* 출처 : https://hianna.tistory.com/432

+ Recent posts