버튼을 한 번 클릭했을 때 여러 개의 체크박스를 동시에 선택하거나 해제하고 싶다면, id 속성과 함께 jQuery() 함수를 활용하면 간단하게 구현할 수 있습니다.
핵심 원리
이 예제에서는 다음과 같은 방식으로 동작합니다.
click()이벤트로 버튼 클릭을 감지합니다.toggleClass()를 사용해 버튼의 상태(선택/해제)를 클래스 존재 여부로 판단합니다.prop("checked", true/false)로 같은 클래스(.isSelected)를 가진 모든 체크박스의 선택 상태를 일괄 변경합니다.- 버튼의 텍스트(
val())도 현재 상태에 맞게 함께 바꿔줍니다.
예제 코드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 체크박스 전체 선택</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.changeColor {
color: red
};
</style>
</head>
<body>
<input type="button" id="selectDemo" value="전체 선택하기" />
<table>
<tr>
<td>
<input type="checkbox" id="CheckBoxId1" class="isSelected" /> Javascript
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId2" class="isSelected" /> MySQL
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId3" class="isSelected" /> MongoDB
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="CheckBoxId4" class="isSelected" /> Python
</td>
</tr>
</table>
<script>
jQuery("#selectDemo").click(function () {
jQuery(this).toggleClass("changeColor");
if (jQuery(this).hasClass("changeColor")) {
jQuery(".isSelected").prop("checked", true);
jQuery(this).val("전체 해제하기");
} else {
jQuery(this).removeClass("changeColor");
jQuery(".isSelected").prop("checked", false);
jQuery(this).val("전체 선택하기");
}
});
</script>
</body>
</html>
실행 방법
위 프로그램을 실행하려면 파일 이름을 “anyName.html”(index.html)로 저장한 뒤, 해당 파일을 마우스 오른쪽 버튼으로 클릭하세요. 그리고 VS Code 편집기에서 “Open with Live Server” 옵션을 선택하면 브라우저에서 바로 결과를 확인할 수 있습니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 나타납니다.

이제 “전체 선택하기” 버튼을 클릭해 보겠습니다.

버튼을 클릭하면 Javascript, MySQL, MongoDB, Python 네 개의 체크박스가 모두 선택되고, 버튼 텍스트가 “전체 해제하기”로 변경됩니다.
다시 “전체 해제하기” 버튼을 클릭하면 아래와 같이 모든 체크박스가 해제됩니다.
