Jquery复选框检查/取消选中 [英] Jquery checkbox check/uncheck

查看:174
本文介绍了Jquery复选框检查/取消选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是正确的方式来检查/取消选中复选框放置在元素内,触发我的功能?
这是我的代码:

 < table id =news_list> 
< tr>
< td>< input type =checkboxname =news [1]/>< / td>
< td> TEXT< / td>
< / tr>< / table>

$(#news_list tr)。click(function(){
var ele = $(this).find('input');
if is(':checked')){
ele.removeAttr('checked');
$(this).removeClass('admin_checked');
} else {
ele .attr('checked','checked');
$(this).addClass('admin_checked');
}
}

问题是我可以检查和取消选中每个框只有一次。在我检查& unchecked有时它仍然添加/删除类,但从来没有检查一个框(即使我点击复选框,而不是表行)。
我尝试过使用.bind('click')触发器,但结果是一样的。



任何解决方案?

解决方案

使用 .prop(),如果我们去你的代码, p>

查看示例 jsbin

  $(#news_list tr)click(function(){
var ele = $(this).find(':checkbox');
if($(':checked')length){
ele.prop('checked',false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked',true);
$(this).addClass('admin_checked');
}
});

更改:


  1. 更改了输入为:checkbox

  2. 比较 复选框的长度


What would be a proper way to check/uncheck checkbox thats placed inside the element, that triggers my function? Here's my code:

<table id="news_list">
<tr>
    <td><input type="checkbox" name="news[1]" /></td>
    <td>TEXT</td>
</tr></table>

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.removeAttr('checked');
        $(this).removeClass('admin_checked');
    }else{
        ele.attr('checked', 'checked');
        $(this).addClass('admin_checked');
    }
});

The problem is i can check and uncheck each box only once. After i've checked & unchecked sometimes it still does add/remove class, but never checking a box again (even when i click on checkbox, not table row). I've tried using .bind('click') trigger, but it's the same result.

Any solutions?

解决方案

use .prop() instead and if we go with your code then compare like this:

look the example jsbin

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

changes:

  1. changed input to :checkbox
  2. comparing the length of the checked checkboxes

这篇关于Jquery复选框检查/取消选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆