How to handle change of checkbox using jQuery?

I have some code

<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" />

javascript:

$(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);
        });
    }
});

How to handle change of checkbox using jQuery ? I need to put the handler to change any checkboxes checked.

[update]

There is a checkbox and a few buttons. Each button can change check box. How to catch an event changing the checkbox?

[Update]

I need handle change checkbox in this example jsfiddle. When I click on the box the message "OK" button is not shown.


Use :checkbox selector:

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

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

}); 

Code: http://jsfiddle.net/s6fe9/


您也可以使用该字段的ID

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

希望,这会有所帮助。

$('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'
});
链接地址: http://www.djcxy.com/p/71034.html

上一篇: 取消选中所有未更新的表单?

下一篇: 如何使用jQuery处理复选框的更改?