jQuery对checkbox的各种操作

jQuery对checkbox的各种操作

1、根据id获取checkbox

1 $("#cbCheckbox1");

2、获取所有的checkbox

1 $("input[type='checkbox']");//or
2 $("input[name='cb']");

3、获取所有选中的checkbox

1 $("input:checkbox:checked");//or
2 $("input:[type='checkbox']:checked");//or
3 $("input[type='checkbox']:checked");//or
4 $("input:[name='ck']:checked");

4、获取checkbox值

1 $("#cbCheckbox1").val();

5、获取多个选中的checkbox值

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

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

1 $("#cbCheckbox1").click(function () {
2     if ($(this).prop("checked")) {
3         alert("选中");
4     } else {
5         alert("没有选中");
6     }
7 });

7、设置checkbox为选中状态

1 $('input:checkbox').attr("checked", 'checked');//or
2 $('input:checkbox').attr("checked", true);

8、设置checkbox为不选中状态

1 $('input:checkbox').attr("checked", '');//or
2 $('input:checkbox').attr("checked", false);

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

1 $("input[type='checkbox']").attr("disabled", "disabled");//or
2 $("input[type='checkbox']").attr("disabled", true);//or
3 $("input[type='checkbox']").prop("disabled", true);//or
4 $("input[type='checkbox']").prop("disabled", "disabled");

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

1 $("input[type='checkbox']").removeAttr("disabled");//or
2 $("input[type='checkbox']").attr("disabled", false);//or
3 $("input[type='checkbox']").prop("disabled", "");//or
4 $("input[type='checkbox']").prop("disabled", false);

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