jQuery 체크박스 예제

by YOO YEONGHWAN

HTML

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
  $(document).ready(function() {
    $("input[type='checkbox']").on('click', function() {
      //checkbox 형태의 input태그 가 클릭될 때 다음 함수를 실행한다.
      var write = '';
      //write 변수 선언
      $("input[type='checkbox']:checked").each(function() {
        //checked 된 input 태그들 각각 write 변수에 내용을 합친다.
        write += $(this).data("name");
      });
      $('#tdbox').val(write);
      //textarea 에 write 에 담긴 내용 셋팅
    });
    $('#alls').on('click', function() {

      var alltext = '';
      $("input[type='checkbox']").prop('checked', true).each(function(index) {
        alltext += $(this).data("name")
      });
      $('#tdbox').val(alltext)
    });
    $('#allr').on('click', function() {
      $('input').prop('checked', false)
      $('#tdbox').val('');
    });
  });

</script>

<!--body 부분 -->

<body>
  <input type="checkbox" name="sport1" value='1' id="sport1" data-name='축구 '>축구
  <input type="checkbox" name="sport1" value='1' id="sport2" data-name='야구 '>야구
  <input type="checkbox" name="sport1" value='1' id="sport3" data-name='농구 '>농구
  <input type="checkbox" name="sport1" value='1' id="sport4" data-name='배구 '>배구
  <input type="checkbox" name="sport1" value='1' id="sport5" data-name='탁구 '>탁구
  <input type="checkbox" name="sport1" value='1' id="sport6" data-name='하키 '>하키
  <br>
  <button id="alls">전체선택</button>
  <button id="allr">전체해제</button>
  <br>
  <input type="checkbox" name="pet1" value='1' id="pet1">강아지
  <input type="checkbox" name="pet2" value='1' id="pet2">고양이
  <input type="checkbox" name="pet3" value='1' id="pet3">토깽이

  <input type="text" name="tdbox" id="tdbox" class="tdbox" size="40">
</body>