728x90

체크박스(checkbox) 전체를 선택/해제하는 jQuery 예제다.

checkall input 박스 변화를 감지하여

$("#check_item").children("input").attr("checked", true); 하거나

$("#check_item").children("input").attr("checked", false); 한다.


attr() 사용시
- HTML attribute 값이 모두 String 으로 넘어옴

prop() 사용시
- Javascript의 프로퍼티 값이 넘어오기 때문에 boolean, date, function 등도 가져올 수 있음


<input type="checkbox" name="" id="chk" checked="checked">

var $checkbox = $('#chk');
console.log($checkbox.attr('checked')); // checked속성의 값을 표시 → "checked"
console.log($checkbox.prop('checked')); // checked프로파티값을 표시 → true or false

체크가 되어있는지 판단을 할경우 .prop()을 사용할 필요가 있다.


체크박스를 전체 선택하고 해제하는 스크립트를 쓰려면 .prop()로 true/false 를 제어하자.

For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as

$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it


For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked and alter that.
With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it


<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>form ex</title>
<style>
body {
    margin: 20px;
    font-family: "맑은 고딕";
}
input[type=checkbox] {
    border: 1px solid #ccc;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
    $("#checkall").change(function(){
        $("input:checkbox").prop('checked', $(this).prop("checked"));
        /*
        if(this.checked){
            $("#check_item").children("input").attr("checked", true); // checked="true"
        }else{
            $("#check_item").children("input").attr("checked", false); // checked="false"
        }
        */
    });
    $("input[name=chkname]").click(function(){ // 개별 선택을 누르면 전체 선택 체크가 풀리게 처리
        if($("#checkall").is(":checked")==true){
            $("input:checkbox[name=checkall]").prop("checked",false);
        }
       console.log($(this).val());
    });

});
</script>
</head>

<body>
<input type="checkbox"  name="checkall" id="checkall" />
<label>All</label>
<div id="check_item">
    <input type="checkbox" name="chkname" value="1" />
    <label>홍길동</label>
    <input type="checkbox" name="chkname" value="2" />
    <label>강감찬</label>
    <input type="checkbox" name="chkname" value="3" />
    <label>이순신</label>
</div>
</body>
</html>

'Web 프로그램 > js, jQuery' 카테고리의 다른 글

jQuery animate  (2) 2018.02.14
jQuery addClass()  (0) 2018.02.04
[jQuery] 테이블 다루기 (find)  (0) 2018.01.15
JavaScript 와 jQuery 비교 정리  (0) 2018.01.15
[Javascript] Form 객체 다루기 (자바스크립트 와 jQuery)  (0) 2017.12.16
블로그 이미지

Link2Me

,