jQuery를 사용하여 확인란 변경을 처리하는 방법은 무엇입니까?


106

코드가 있습니다

<input type="checkbox" id="chk" value="value" />
<label for="chk">Value </label>
<br/>
<input type="button" id="But1" value="set value" />
<br />
<input type="button" id="But2" value="read checked" />

자바 스크립트 :

$(document).ready(function () {
    console.log("Ready ...");
    registerHandlers();

    function registerHandlers() {
        $('#But1').click(function () {
            $('#chk').prop('checked', !$('#chk').is(':checked'));
        });
        $('#But2').click(function () {
            var chk1 = $('#chk').is(':checked');
            console.log("Value : " + chk1);
        });

        $('input[type="checkbox"]').change(function () {
            var name = $(this).val();
            var check = $(this).prop('checked');
            console.log("Change: " + name + " to " + check);
        });
    }
});

jQuery를 사용하여 확인란 변경을 처리하는 방법은 무엇입니까? 체크 박스를 변경하려면 핸들러를 넣어야합니다.

[최신 정보]

체크 박스와 몇 개의 버튼이 있습니다. 각 버튼은 확인란을 변경할 수 있습니다. 체크 박스를 변경하는 이벤트를 잡는 방법은 무엇입니까?

[최신 정보]

이 예제 jsfiddle 에서 핸들 변경 확인란이 필요합니다 . 상자를 클릭하면 "확인"버튼이 표시되지 않습니다.


나는 당신의 문제를 정말로 이해하지 못합니까? 체크 박스가 변경되면 어떻게 되나요?
Niklas 2012

뭐가 문제 야? 이 코드는 잘 작동에 나타납니다
JaredPar

2
질문을 바꿔 주시겠습니까? 이미 $ ( 'input [type = "checkbox"]'). change 핸들러가 있습니다. 무엇이 잘못 되었나요?
Madman 2012

버튼 확인란을 변경하면 변경 이벤트가 발생하지 않습니다
BILL

3
FYI; $('#chk').prop('checked')속성 값이 아닌 부울을 반환합니다. 참조 api.jquery.com/prop
스테판

답변:


163

:checkbox선택기 사용 :

$(':checkbox').change(function() {

        // do stuff here. It will fire on any checkbox change

}); 

코드 : http://jsfiddle.net/s6fe9/


75
... this.checked확인란의 선택 여부를 결정하는 데 매우 유용합니다.
Stefan

1
여러 핸들러를 등록 할 수 있습니까?
BILL

1
2015 년에도 여전히 권장 되나요?
Eugen Sunic 2015 년

2
API가 변경된 것 같지 않으니 그렇습니다.
Samich

이것은 $ (document) .ready (function () ... 안에 있어야합니다. 저에게 맞습니까?
kaya

66

필드의 ID도 사용할 수 있습니다.

$('#checkbox1').change(function() {
   if($(this).is(":checked")) {
      //'checked' event code
      return;
   }
   //'unchecked' event code
});

17

희망, 이것이 도움이 될 것입니다.

$('input[type=checkbox]').change(function () {
    if ($(this).prop("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

6
jQuery 1.6부터 $ (this) .prop ( "checked")를 사용하는 것이 좋습니다. 체크 박스의 실제 상태에 따라 동적으로 변경됩니다.
hrabinowitz

3
.attr ( "checked")는 사용자가 클릭 할 때 업데이트되지 않기 때문에 올바르지 않습니다. @hrabinowitz의 의견을 확인합니다.
Adrien

7
$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

1
게시하기 전에 자신의 코드가 작동하는지 확인하십시오. 당신의 선택기와 눈부신 문제는 ...이
조나단

live ()는 더 이상 사용되지 않습니다.
guettli

4
$('#myForm').on('change', 'input[type=checkbox]', function() {
    this.checked ? this.value = 'apple' : this.value = 'pineapple';
});

3
답변을 정교하게 작성하십시오. 코드 전용 솔루션은 설명이 없기 때문에 삭제 될 가능성이 더 높으며 문제가있는 경우 수정하십시오.
rekaszeru

죄송합니다 @rekaszeru 다음에 더 잘 할게요
Everton ZP

0

나에게 removeProp이 Chrome에서 제대로 작동하지 않는 것 같습니다 : jsfiddle

        $('#badBut1').click(function () {
        checkit('Before');
        if( $('#chk').prop('checked') )
        {
          $('#chk').removeProp('checked');
        }else{
            $('#chk').prop('checked', true);
        }
        checkit('After');
    });
    $('#But1').click(function () {
        checkit('Before');
        if( $('#chk').prop('checked') )
        {
          $('#chk').removeClass('checked').prop('checked',false);
        }else{
            $('#chk').addClass('checked').prop('checked', true);
        }
        checkit('After');
    });

    $('#But2').click(function () {
        var chk1 = $('#chk').is(':checked');
        console.log("Value : " + chk1);
    });

    $('#chk').on( 'change',function () {
        checkit('Result');
    });
    function checkit(moment) {
        var chk1 = $('#chk').is(':checked');
        console.log(moment+", value = " + chk1);
    };

: A (외부에서) 이벤트없이 체크 박스를 전환하는 방법 jsfiddle.net/k91k0sLu/1
belloeil 로랑

0

이름으로 라디오 가치를 얻다

  $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.