如何使用jQuery处理复选框的更改?

BIL*_*ILL 104 checkbox jquery

我有一些代码

<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" />
Run Code Online (Sandbox Code Playgroud)

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);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

如何使用jQuery处理复选框的更改?我需要把处理程序更改为选中的任何复选框.

[更新]

有一个复选框和几个按钮.每个按钮都可以更改复选框.如何捕捉更改复选框的事件?

[更新]

我需要在此示例jsfiddle中使用 handle change复选框.当我单击该框时,不显示消息"确定"按钮.

Sam*_*ich 156

使用:checkbox选择器:

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

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

}); 
Run Code Online (Sandbox Code Playgroud)

代码:http://jsfiddle.net/s6fe9/

  • ...和`this.checked`非常有用,可以确定是否选中了复选框. (74认同)
  • 它看起来不像API已经改变,所以是的. (2认同)

Pin*_*rma 62

您也可以使用该字段的ID

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


Lok*_*dav 16

希望,这会有所帮助.

$('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'
});
Run Code Online (Sandbox Code Playgroud)

  • 从jQuery 1.6开始,最好使用$(this).prop("checked"),因为它将随复选框的实际状态动态变化. (6认同)
  • .attr("checked")不正确,因为它没有随用户点击而更新.我确认了@ hrabinowitz的评论. (3认同)

Arj*_*jun 8

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

    if (this.checked) {

      //do your stuff

     }
});
Run Code Online (Sandbox Code Playgroud)


Eve*_* P. 6

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

  • 请详细说明您的答案:仅代码解决方案更有可能被删除,因为它们不解释,只是修复(如果有)。 (3认同)