[css] 체크박스 모두체크하기

beomhak lee·2024년 2월 21일

work_tip

목록 보기
9/37

체크박스 모두 체크하는 방법

ex html

 <div>
    <div class="allfruit">
      <input type="checkbox" id="allfruit"><label for="allfruit">과일</label>
    </div>
    <div class="water frs">
      <input type="checkbox" id="water"><label for="water">수박</label>
    </div>
    <div class="melon frs">
      <input type="checkbox" id="melon"><label for="melon">참외</label>
    </div>
    <div class="apple frs">
      <input type="checkbox" id="apple"><label for="apple">사과</label>
    </div>
  </div>



  1. 첫번째로 모두체크할때 실행할 함수를 만들어준다.
function AllFuc() {
      const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
      const checkbox = $('.frs > input[type="checkbox"]');

      Allcheckboxs.change(function(){
        if(this.checked){
          checkbox.prop('checked',true)
          checkbox.parent().addClass('on')
        }else{
          checkbox.prop('checked',false)
          checkbox.parent().removeClass('on')
        }
      })
    }

모두체크박스가 변화할때 checked 상태면 각 체크박스를 checked true 처리하고 on클래스추가한다. checked 상태가 아니면 checked false처리후 on 클래스를 제거한다.



2. 체크박스들의 체크상태를 조사해 전체선택 버튼의 체크상태를 갱신하는 함수를 만든다

function checkboxUpdate(){
      const checkboxCount = $('.frs > input[type="checkbox"]').length;
      const checkedboxCount = $('.frs > input[type="checkbox"]:checked').length;
      const Allcheckboxs = $('.allfruit > input[type="checkbox"]');

      if(checkboxCount == checkedboxCount){
        Allcheckboxs.prop('checked',true)
      }else{
        Allcheckboxs.prop('checked',false)
      }
    }

if 함수로 check가 되어있는 박스와 안되어있는박스의 갯수를 조사해
모두체크박스 부분이 true false 체크된다.



체크박스의 변화를 감지하는 함수에 방금만든 함수를 넣어주고, 각 박스의 클래스를 추가 제거 한다.

checkbox.change(function(){
  if(this.checked){
    $(this).parent().addClass('on')
  }else{
    $(this).parent().removeClass('on');
  }
  checkboxUpdate()
})



ALL VIEW

// 체크박스들의 체크상태를 조사해 전체선택 버튼의 체크상태를 갱신
    function checkboxUpdate(){
      const checkboxCount = $('.frs > input[type="checkbox"]').length;
      const checkedboxCount = $('.frs > input[type="checkbox"]:checked').length;
      const Allcheckboxs = $('.allfruit > input[type="checkbox"]');

      if(checkboxCount == checkedboxCount){
        Allcheckboxs.prop('checked',true)
      }else{
        Allcheckboxs.prop('checked',false)
      }
    }

    function AllFuc() {
      const Allcheckboxs = $('.allfruit > input[type="checkbox"]');
      const checkbox = $('.frs > input[type="checkbox"]');

      Allcheckboxs.change(function(){
        if(this.checked){
          checkbox.prop('checked',true)
          checkbox.parent().addClass('on')
        }else{
          checkbox.prop('checked',false)
          checkbox.parent().removeClass('on')
        }
      })

      checkbox.change(function(){
        if(this.checked){
          $(this).parent().addClass('on')
        }else{
          $(this).parent().removeClass('on');
        }
        checkboxUpdate()
      })
    }

    AllFuc();

0개의 댓글