새소식

🏫 Library/🥏 jQuery

jquery checkbox 체크, 체크여부, 전체체크 방법?

728x90

🤔 Question

👉 jQuery를 사용하면 체크박스의 체크, 체크 여부 확인, 전체 체크 기능 등을 쉽게 구현할 수 있습니다. 아래는 각각의 기능을 예제 코드와 함께 설명한 내용입니다.

 

🎯 체크박스 체크 방법?

👉 특정 체크박스를 체크하거나 체크 해제하려면 .prop() 메서드를 사용합니다.

// 체크박스를 체크함
$('#checkbox1').prop('checked', true);

// 체크박스를 체크 해제함
$('#checkbox1').prop('checked', false);

 

🎯 체크박스 체크 여부

👉 체크박스가 체크되어 있는지 확인하려면 .prop() 또는 .is() 메서드를 사용할 수 있습니다.

// 체크 여부 확인
if ($('#checkbox1').prop('checked')) {
    console.log('체크됨');
} else {
    console.log('체크 안 됨');
}

// .is()를 사용한 방법
if ($('#checkbox1').is(':checked')) {
    console.log('체크됨');
}

 

🎯 전체 체크 (전체 선택)

👉 전체 체크 기능은 모든 체크박스를 동시에 체크하거나 체크 해제할 수 있도록 만듭니다.

예시를 하나 전달드리겠습니다.

<input type="checkbox" id="checkAll"> 전체 선택<br>
<input type="checkbox" class="checkItem"> 항목 1<br>
<input type="checkbox" class="checkItem"> 항목 2<br>
<input type="checkbox" class="checkItem"> 항목 3<br>

<script>
    // "전체 선택" 체크박스를 클릭했을 때 모든 체크박스의 상태를 변경
    $('#checkAll').on('change', function () {
        $('.checkItem').prop('checked', this.checked);
    });

    // 개별 체크박스를 모두 선택 또는 해제했을 때 "전체 선택" 체크박스 상태 업데이트
    $('.checkItem').on('change', function () {
        $('#checkAll').prop('checked', $('.checkItem:checked').length === $('.checkItem').length);
    });
</script>

 

🎯 추가 팁:  체크된 항목의 값을 배열로 가져오기

👉 선택된 체크박스들의 값을 배열로 가져오는 방법입니다.

// 체크된 항목의 값을 배열로 가져오기
var selectedValues = $('.checkItem:checked').map(function () {
    return $(this).val();
}).get();

console.log(selectedValues);

 

If I was of any help to you, please buy me coffee 😿😢😥

If you have any questions, please leave them in the comments

🧭 References

[1] reference : https://doctorson0309.tistory.com/

[2] Ads : https://www.youtube.com/watch?v=jEBJsNxtVGk

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.