jQuery对checkbox的各种技巧

原创
小哥 3年前 (2022-11-02) 阅读数 47 #大杂烩

//注意: 操作checkbox的checked,disabled属性时jquery1.6对于以前的版本attr,1.6以上(含)是推荐的。prop

//1、根据id获取checkbox
$("#cbCheckbox1");

//2,得到全部。checkbox
$("input[type=checkbox]");//or
$("input[name=cb]");

//3,全部选中checkbox
$("input:checkbox:checked");//or
$("input:[type=checkbox]:checked");//or
$("input[type=checkbox]:checked");//or
$("input:[name=ck]:checked");

//4、获取checkbox值
//用.val()例如,它可以是:
$("#cbCheckbox1").val();

//5,选择多个checkbox值
var vals = [];
$(input:checkbox:checked).each(function (index, item) {
vals.push($(this).val());
});

//6、判断checkbox是否勾选(jquery 1.6以前版本 用  $(this).attr("checked"))
$("#cbCheckbox1").click(function () {
if ($(this).prop("checked")) {
alert("选中");
} else {
alert("没有选中");
}
});

//7、设置checkbox已选中
$(input:checkbox).attr("checked", checked);//or
$(input:checkbox).attr("checked", true);

//8、设置checkbox未选中
$(input:checkbox).attr("checked", );//or
$(input:checkbox).attr("checked", false);

//9、设置checkbox已禁用(jquery<1.6用attr,jquery>=1.6建议用prop)
$("input[type=checkbox]").attr("disabled", "disabled");//or
$("input[type=checkbox]").attr("disabled", true);//or
$("input[type=checkbox]").prop("disabled", true);//or
$("input[type=checkbox]").prop("disabled", "disabled");

//10、设置checkbox处于启用状态(jquery<1.6用attr,jquery>=1.6建议用prop)
$("input[type=checkbox]").removeAttr("disabled");//or
$("input[type=checkbox]").attr("disabled", false);//or
$("input[type=checkbox]").prop("disabled", "");//or
$("input[type=checkbox]").prop("disabled", false);


1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 3 4 5 6 7

jQuery操作checkbox 8

9 10 11 12 13 14
15 <input type="button" id="btnDisabled" value="禁用" οnclick="fn_disabled();" /> 16 <input type="button" id="Button1" value="启用" οnclick="fn_enable();" />
17 <input type="button" id="Button2" value="获取所选值" οnclick="getCheckedValues();" />
18 <input type="button" id="Button3" value="选择第二个" οnclick="checkedSecond();" /> 19 <input type="button" id="Button4" value="取消选择第二个" οnclick="uncheckedSecond();" />
20 21 22 23

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门