18. 8. 27.

약관동의(Javascript)

querySelectorAll 가 IE 8 부터 사용가능하기 때문에 8부터 적용가능
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>약관동의</title>
    <script type="text/javascript">
        window.onload = function () {
            var chks = document.querySelectorAll("input[name=chk]");
            var cllchkbox = document.getElementById("allChk");
            cllchkbox.onclick = function () {
                if (this.checked) {
                    for (var i = 0; i < chks.length; i++) {
                        chks[i].checked = true;
                    }
                } else {
                    for (var i = 0; i < chks.length; i++) {
                        chks[i].checked = false;
                    }
                }
            }
            function chkclick() {
                var chkarr = chks;
                var chkcnt = 0;
                for (var i = 0; i < chkarr.length; i++) {
                    if (chkarr[i].checked) { chkcnt++; }
                }
                if (chkarr.length == chkcnt) {
                    cllchkbox.checked = true;
                } else {
                    cllchkbox.checked = false;
                }
            }
            for (var i = 0; i < chks.length; i++) {
                var elm = chks[i];
                elm.onclick = function () {
                    chkclick();
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1">
        <label><input type="checkbox" id="allChk" />모든 약관동의</label>
        <div>약관1</div>
        <label><input type="checkbox" name="chk" /> 동의합니다.</label>
        <div>약관2</div>
        <label><input type="checkbox" name="chk" /> 동의합니다.</label>
        <div>약관3</div>
        <label><input type="checkbox" name="chk" /> 동의합니다.</label>
    </form>
</body>
</html>