728x90
    
    
  반응형
    
    
    
  
간만에 하는 jQuery 포스팅.
바로 본론으로 가봅시다.
$(document).ready(function() {
	$("#cbx_chkAll").click(function() {
		if($("#cbx_chkAll").is(":checked")) $("input[name=chk]").prop("checked", true);
		else $("input[name=chk]").prop("checked", false);
	});
	$("input[name=chk]").click(function() {
		var total = $("input[name=chk]").length;
		var checked = $("input[name=chk]:checked").length;
		if(total != checked) $("#cbx_chkAll").prop("checked", false);
		else $("#cbx_chkAll").prop("checked", true); 
	});
});
헤더에 있는 체크박스를 클릭하는 이벤트 설명은 하단에 있는 게시글에 있으니 참고 부탁드리구요~
https://drcode-devblog.tistory.com/3
여기에 기능이 더해진 것은
이제 밑에 목록으로 있는 체크박스들을 전부 다 선택 시 헤더에 있는 체크박스가 선택되도록 하는 기능은
갯수 비교를 하면 됩니다.
목록에 있는 체크박스 갯수 와 목록에 있는 것 중 체크된 체크박스 갯수를 비교해서
일치하면 헤더에 있는 체크박스를 체크되게 하고
일치하지 않으면 체크박스를 해제하면 됩니다.
| 체크박스 테스트 | |
|---|---|
| 체크 1 | |
| 체크 2 | |
| 체크 3 | 
전체 소스코드
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>체크박스 연습</title>
	<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#cbx_chkAll").click(function() {
				if($("#cbx_chkAll").is(":checked")) $("input[name=chk]").prop("checked", true);
				else $("input[name=chk]").prop("checked", false);
			});
			
			$("input[name=chk]").click(function() {
				var total = $("input[name=chk]").length;
				var checked = $("input[name=chk]:checked").length;
				
				if(total != checked) $("#cbx_chkAll").prop("checked", false);
				else $("#cbx_chkAll").prop("checked", true); 
			});
		});
	</script>
</head>
<body>
	<table>
		<thead>
			<tr>
				<th><input type="checkbox" id="cbx_chkAll" /></th>
				<th>체크박스 테스트</th>
			</tr>	
		</thead>
		<tbody>
			<tr>
				<td><input type="checkbox" name="chk"></td>
				<td>체크 1</td>
			</tr>
			<tr>
				<td><input type="checkbox" name="chk"></td>
				<td>체크 2</td>
			</tr>
			<tr>
				<td><input type="checkbox" name="chk"></td>
				<td>체크 3</td>
			</tr>
		</tbody>
	</table>
</body>
</html>
728x90
    
    
  반응형
    
    
    
  'javascript, jQuery > jQuery' 카테고리의 다른 글
| [jQuery] 제이쿼리로 id값 받기 (0) | 2021.04.15 | 
|---|---|
| [jQuery] 제이쿼리를 이용하여 선택한 체크박스 항목 가져오기(인덱스 가져오기, 전체선택 해제) (1) | 2020.11.20 | 
| jQuery를 이용하여 체크박스 전체선택, 전체해제 기능 구현 (0) | 2020.11.17 | 
| jQuery CDN 붙여넣기 (1) | 2020.11.16 | 
										
									
										
									
										
									
댓글