반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

그럴 수도 있지

[Javascript] 체크박스(checkbox) 전체 선택 및 해제, 전체 선택 판단) 본문

Javascript

[Javascript] 체크박스(checkbox) 전체 선택 및 해제, 전체 선택 판단)

디벅 2022. 6. 21. 22:34
반응형

1. 체크 박스를 전체 선택 혹은 전체 해제
2. 전체 체크 후 한 건이라도 체크를 풀 경우 전체 체크박스의 체크가 해제 

위와 같이 체크박스를 전체 선택하거나 해제, 그리고 전체 선택 했는지 여부를 판단하는 경우가 많아서 나 같은 경우는 공통 함수로 빼서 여기저기 화면에서 사용하고 있다.

 

1. 기본 화면

2. 전체 선택

3. 전체 해제

4. 전체 선택 후 하나만 체크 해제(전체 체크 박스가 풀려야함)

5. disabled 된 내역은 제외

 

HTML 
<!DOCTYPE html>
<html>
  <head>
    <script src="checkbox.js"  type="text/javascript"></script>
  </head>
  <style>
  table {
    border-collapse: collapse;
    text-align:center;
    font-family: Arial, Helvetica, sans-serif;
    width: 200px;
    font-size: 10pt;
  }

  th, td{
    border: #cccccc 1px solid;
    background-color:#F3FAFD;
    padding : 0.4em;
  }

  td {
    background-color: #FFFFFF;
  }
  </style>
  <div>
    <table style="BORDER: #cccccc 1px solid; border-collapse: collapse;">
      <tr>
        <!-- 체크박스 이름과 전체 체크 박스 선택 값을 넘겨준다. -->
        <th style="width:30px"><input type='checkbox' id="chkAll" onclick="allCheckboxes('chk[]', this.checked)"></th>
        <th>항목</th>
      </tr>
      <tr>
        <th><input type='checkbox' name = 'chk[]' onclick="isAllCheck(this.name, 'chkAll');"></th>
        <td>사과</td>
      </tr>
      <tr>
        <th><input type='checkbox' name = 'chk[]' onclick="isAllCheck(this.name, 'chkAll');"></th>
        <td>딸기</td>
      </tr>
      <tr>
        <th><input type='checkbox' name = 'chk[]' onclick="isAllCheck(this.name, 'chkAll');"></th>
        <td>포도</td>
      </tr>
      <tr>
        <th><input type='checkbox' name = 'chk[]' disabled onclick="isAllCheck(this.name, 'chkAll');"></th>
        <td>메론</td>
      </tr>
      <tr>
        <th><input type='checkbox' name = 'chk[]' onclick="isAllCheck(this.name, 'chkAll');"></th>
        <td>자두</td>
      </tr>
    </table>
  </div>

</html>
javscript
//체크박스 전체 선택/해제
function allCheckboxes(boxNames, chkMode){
  const el = document.getElementsByName(boxNames);
  for(let i = 0; i < el.length; i++){          
   if(!el[i].disabled){
     el[i].checked = chkMode;	
   }
  }
}

//전체 체크 여부
function isAllCheck(boxNames, allChkName){
  const el = document.getElementsByName(boxNames);
  let checkboxCnt = 0;
  let checkedCnt = 0;
  for(let i = 0; i < el.length; i++){
    if(!el[i].disabled){
      checkboxCnt += 1;
      if(el[i].checked){
        checkedCnt += 1;
      }
    }
  }
  
  let chkMode = false;
  //체크박스 개수와 체크 된 체크박스 개수와 일치할 경우
  if(checkboxCnt == checkedCnt){
    chkMode = true;
  } else {  
    chkMode = false;
  }  
  //일치할 경우 천제 체크 박스는 체크, 일치하지 않을 경우 해제
  document.getElementById(allChkName).checked = chkMode;
}

 

예시 파일

 

checkbox.html
0.00MB
checkbox.js
0.00MB

반응형