반응형
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./index.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Gaegu&family=Gamja+Flower&display=swap" rel="stylesheet">
</head>
<body>
<div class="wrap">
<div class="outerbox" >
<div class="innerbox">
<h2 class="main">게시판</h2>
<div class="mainbox">
<table id="table1">
<tr id ="fields" class="tb">
<td class="td0">
<span>All</span>
<span><input name="chk" type="checkbox" onclick="checkAll(this)"></span>
</td>
<td class="td1">번호</td>
<td class="td2">제목</td>
<td class="td3">작성자</td>
<td class="td4">수정 날짜</td>
<td class="td4">작성 날짜</td>
<td class="td5">조회수</td>
</tr>
<tr class="tb">{% for item in board_db %}
<td class="td1"><input name="chk" type="checkbox" ></td>
<td class="td1">{{item.idx2}}</td>
<td class="td2" id="aa"><a href="/view?idx={{item.idx}}">{{item.subject}}</a></td>
<td class="td3">{{item.writer}}</td>
<td class="td4">{{item.motoday}}</td>
<td class="td4">{{item.today}}</td>
<td class="td5">{{item.hit}}</td>
</tr>{% endfor %}
</table>
<div class="btnbox">
<button class="btn"><a href="/">돌아가기</a></button>
<button class="btn"><a href="/write">글쓰기</a></button>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
let check = false;
// function checkAll(){
// let chk = document.getElementsByName("chk[]");
// console.log(chk);
// if(check==false){
// check=true;
// for(let i=0; i<chk.length; i++){
// chk[i].checked=true;
// }
// }else{
// check=false;
// for(let i=0; i<chk.length; i++){
// chi[i].checked=false;
// }
// }
// }
function checkAll(checkAll){
let checkboxes=document.getElementsByName("chk");
console.log(checkboxes);
checkboxes.forEach((checkbox)=>{
console.log(checkbox );
checkbox.checked=checkAll.checked;
})
}
</script>
</body>
</html>
게시판을 만들다가 checkbox 를 쭈르룩 만들고 전체 선택 / 해제를 하기위한 JavaScript 는 위와 같다.
기본 참고한 예제는 ↓↓↓↓
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="checkbox" name="animal" value="select all" onclick="checkAll(this)">select all
<br/>
<input type="checkbox" name="animal" value="dog" >개
<br/>
<input type="checkbox" name="animal" value="cat"> 고양이
<script type="text/javascript">
function checkAll(checkAll){
let checkboxes = document.getElementsByName("animal");
checkboxes.forEach((checkbox)=>{
checkbox.checked=checkAll.checked;
})
}
</script>
</body>
</html>
getElementsByName 으로 name="animal"인 elements의 NodeList를 만들고 forEach구문을 사용해서 각각의 요소 (checkbox)에 적용
참고글
반응형