用jQuery对checkbox的checked进行操作

注意: 操作checkbox的checked,disabled属性时jquery1.6以前版本用attr,    1.6以上(包含)建议用prop

1、根据id获取checkbox

 $("#Checkbox1");

2、获取所有的checkbox    

$("input[type='checkbox']");//或者$(":checkbox");

3、获取所有选中的checkbox  

  $("input:checkbox:checked");
  //或$("input[type='checkbox']:checked");
  //或$("input:[type='checkbox']:checked");

4、获取checkbox值
    用.val()获取

$("#Checkbox").val();

 5、获取多个选中的checkbox值   

    var vals = [];
    $('input:checkbox:checked').each(function (index, item) {
        vals.push($(this).val());
    });

6、判断checkbox是否选中(jquery 1.6以前版本 用  $(this).attr("checked") 

  用prop查:选中时checked值为true,未选中时checked值为false

$("#cbCheckbox1").click(function () {
    if ($(this).prop("checked")) {
            alert("选中");
    } else {
            alert("没有选中");
    }
});

用attr查:选中checked值为checked,未选中时checked值为undefined

7、设置checkbox为选中状态  

$('input:checkbox').attr("checked", 'checked');//或$('input:checkbox').prop("checked", true);

8、设置checkbox为不选中状态

扫描二维码关注公众号,回复: 5425465 查看本文章
$('input:checkbox').prop("checked", false);//或$('input:checkbox').attr("checked", '');

 9、设置checkbox为禁用状态(jquery<1.6用attr,jquery>=1.6建议用prop)
   

 $("input[type='checkbox']").attr("disabled", "disabled");
//或$("input[type='checkbox']").attr("disabled", true);
//或$("input[type='checkbox']").prop("disabled", true);
//或$("input[type='checkbox']").prop("disabled", "disabled");

10、设置checkbox为启用状态(jquery<1.6用attr,jquery>=1.6建议用prop)
   

$("input[type='checkbox']").removeAttr("disabled");
//或$("input[type='checkbox']").attr("disabled", false);
//或$("input[type='checkbox']").prop("disabled", "");
//或$("input[type='checkbox']").prop("disabled", false);

猜你喜欢

转载自blog.csdn.net/weixin_44390947/article/details/88173579