jQuery操作checkbox选择

来源:互联网 发布:上升三法选股公式源码 编辑:程序博客网 时间:2024/05/22 11:49

attr 更加jQuery版本 缓存prop

1. 判断checkbox(复选框)是否被选中 

很多朋友判断  if($("#id").attr("checked")=="true") 这个是错误的,其实应该是 if($("#id").attr("checked")==true)

if($("#id").is(":checked")== true)

2. 全选

  $("[name = chkItem]:checkbox").attr("checked", true);

3、全不选

$("[name = chkItem]:checkbox").attr("checked", false);


 

$("[name = chkItem]:checkbox").each(function () {
                    $(this).attr("checked", !$(this).attr("checked"));
                });

5.选中所有奇数

 $("[name='checkbox']:even").attr("checked",'true');


6.获得选中的所有值

$("[name='checkbox'][checked]").each(function(){
     str+=$(this).val()+""r"n";
    })


7、获取单个checkbox选中项(三种写法)

$("input:checkbox:checked").val()
或者
$("input:[type='checkbox']:checked").val();
或者
$("input:[name='ck']:checked").val();


8.获取多个checkbox选中项

$('input:checkbox').each(function() {
        if ($(this).attr('checked') ==true) {
                alert($(this).val());
        }
});


9.设置第一个checkbox 为选中值

$('input:checkbox:first').attr("checked",'checked');

或者
$('input:checkbox').eq(0).attr("checked",'true');

10.根据索引值设置任意一个checkbox为选中值

$('input:checkbox).eq(索引值).attr('checked', 'true');索引值=0,1,2....
或者
$('input:radio').slice(1,2).attr('checked', 'true');

11、选中多个checkbox同时选中第1个和第2个的checkbox
$('input:radio').slice(0,2).attr('checked','true');

12、根据Value值设置checkbox为选中值
$("input:checkbox[value='1']").attr('checked','true');