본문 바로가기
JavaScript

[JavaScript] 체크박스 전체 선택하기 예제

by teamnova 2022. 3. 15.

안녕하세요

 

오늘은 체크박스 전체선택 기능에 대해서 알아보겠습니다.

 

*결과


 

1. type = "checkbox"

<label><input type="checkbox" /> 동의 1-1</label>

기본적으로 위 코드로 체크박스를 화면에 나타낼 수 있고 클릭 명령을 받아서 체크 여부를 보여줍니다.

 

2. <script> 태그

우선 <script> 태그를 사용하여 웹브라우저가 자바스크립트를 인식하게 하고

src 옵션으로 라이브러리를 참조할 수 있도록 합니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

 

 

3. function($){}(jQuery)

function($){}(jQuery) 형태는 즉시 실행함수입니다.

Immediately-invoked function expression

 

(function ($) {
    $.fn.cbFamily = function (children) {
        return this.each(function () {
            var $this = $(this);
            var els;
                if ($.isFunction(children)) {
                    els = children.call($this);
                } else {
                    els = $(children);
                }
            $this.bind("click.cbFamily", function () {
                els.prop('checked', this.checked).change();
            });

            function checkParent() {
                $this.prop('checked',
                    els.length == els.filter("input:checked").length);
            }

            els.bind("click.cbFamily", function () {
                if ($this.prop('checked') && !this.checked) {
                    $this.prop('checked', false).change();
                }
                if (this.checked) {
                    checkParent();
                    $this.change();
                }
            });

            // Check parents if required on initialization
            checkParent();
        });
    };
})(jQuery);

 

함수를 정의하자마자 바로 실행하는 것이죠. 이렇게 하면 $를 지역변수로 활용하여 다른 라이브러리와 충돌할 일도 방지하게 됩니다.

 

 

4. prop 함수

prop 함수를 사용하여 현재 체크박스의 체크 여부를 true, false로 가져오고 그 값을 change 합니다.

 function checkParent() {
                $this.prop('checked',
                    els.length == els.filter("input:checked").length);
            }

 

5. this

this는 전역객체를 의미하는 window와 같습니다.

그래서 어떤 객체 안에 있는 메소드에서 사용되는 this는 해당 객체를 의미하게 됩니다.

 

 

6. 전체 코드

<!doctype html>
<html lang="kr">
	<head>
	<meta charset="UTF-8">
	<title>체크박스 예제</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script type="text/javascript">
(function ($) {
    $.fn.cbFamily = function (children) {
        return this.each(function () {
            var $this = $(this);
            var els;
                if ($.isFunction(children)) {
                    els = children.call($this);
                } else {
                    els = $(children);
                }
            $this.bind("click.cbFamily", function () {
                els.prop('checked', this.checked).change();
            });

            function checkParent() {
                $this.prop('checked',
                    els.length == els.filter("input:checked").length);
            }

            els.bind("click.cbFamily", function () {
                if ($this.prop('checked') && !this.checked) {
                    $this.prop('checked', false).change();
                }
                if (this.checked) {
                    checkParent();
                    $this.change();
                }
            });

            // Check parents if required on initialization
            checkParent();
        });
    };
})(jQuery);


</script>
</head>
<body>

<section>
  <h3><label><input type="checkbox" /> 동의1 전체선택</label></h3>
  <div class="children">
    <label><input type="checkbox" /> 동의 1-1</label>    
    <label><input type="checkbox" /> 동의 1-2</label>    
    <label><input type="checkbox" /> 동의 1-3</label>
  </div>
</section>
<section>
  <h3><label><input type="checkbox" /> 동의2 전체선택</label></h3>
  <div class="children">
    <label><input type="checkbox" checked="checked" /> 동의 2-1</label>    
    <label><input type="checkbox" checked="checked" /> 동의 2-2</label>    
    <label><input type="checkbox" checked="checked" /> 동의 2-3</label>
  </div>
</section>

<script type="text/javascript">
  $("h3 input:checkbox").cbFamily(function (){
    return $(this).parents("h3").next().find("input:checkbox");
  });
</script>



</body>
</html>