1. 程式人生 > 實用技巧 >jQuery對checkbox的各種操作

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