jQuery复选框选中状态改变事件

757

当复选框被选中/取消选中时,我希望在客户端触发一个事件:

$('.checkbox').click(function() {
  if ($(this).is(':checked')) {
    // Do stuff
  }
});

基本上我想让它在页面上的每个复选框上都发生。这种点击并检查状态的触发方法可行吗?

我认为必须有一种更简洁的jQuery方式。有人知道解决方案吗?


33
@Arif,我认为它们并不是重复的,因为链接的问题是关于获取复选框状态的,而这个问题是关于已选事件的。 - Rachel
1
我总是不得不搜索这个已检查的属性,有许多方法可以实现这一点如此写在这里 - user3199690
13个回答

2
也许这对你来说是另一种选择。
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`

2
尝试使用这个jQuery验证。

$(document).ready(function() {
  $('#myform').validate({ // initialize the plugin
    rules: {
      agree: {
        required: true
      }

    },
    submitHandler: function(form) {
      alert('valid form submitted');
      return false;
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>

<form id="myform" action="" method="post">
  <div class="buttons">
    <div class="pull-right">
      <input type="checkbox" name="agree" /><br/>
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>
    </div>
  </div>
  <button type="submit">Agree</button>
</form>


0

关键是:使用prop而不是attr来查询checked状态,例如:

  • 正确的方式:jQuery('#my_check_tag').prop('checked') // 返回正确的状态
  • 错误的方式:jQuery('#my_check_tag').attr('checked') // 总是返回未定义

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接