这篇文章主要介绍了jQuery获取复选框被选中数量及判断选择值的方法,结合实例形式分析了jQuery操作复选框进行判定与统计的相关技巧,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了jQuery获取复选框被选中数量及判断选择值的方法。分享给大家供大家参考,具体如下:
获取复选框被选中值
$("#btn5").click(function(){
var str="";
$("[name='checkbox'][checked]").each(function(){
str+=$(this).val()+",";
})
$("#dd").val(str)
})
JQuery获取被选中复选框checkbox的个数
通过jQuery获取checkbox选中项的个数,需要用到jQuery的size()方法或length属性,下面的例子是通过length属性获得checkbox选中项的个数
- 看电视
- 看电影
- 上网
- 爬山
- 游乐场
- 逛街
- 聚会
$(document).ready(function(){
$('input[type=checkbox]').click(function(){
$(this).attr('disabled','disabled');
if($("input[name='test']:checked").length >= 3)
{
$("input[name='test']").attr('disabled','disabled');
}
});
$("#count").click(function(){
$('input').live('click',function(){
alert($('input:checked').length);
});
})
})
效果二(选超过三个做弹窗提示):
$('input[type=checkbox]').click(function(){
if($("input[name='test']:checked").length >= 4)
{
$(this).removeAttr("checked");
alert("最多选3个!")}
});
jquery如何判断checkbox(复选框)是否被选中/全选/返选/取消全选:
在html 如果一个复选框被选中 是 checked="checked"。
但是我们如果用jquery alert($("#id").attr("checked")) 会提示您是true而不是checked
所以很多朋友判断:
if($("#id").attr("checked")=="true")
这个是错误的,其实应该是:
if($("#id").attr("checked")==true)
例子里面包括了一下几个功能。
代码
jQuery(function($){
//全选
$("#btn1").click(function(){
$("input[name='checkbox']").attr("checked","true");
})
//取消全选
$("#btn2").click(function(){
$("input[name='checkbox']").removeAttr("checked");
})
//选中所有基数
$("#btn3").click(function(){
$("input[name='checkbox']:even").attr("checked","true");
})
//选中所有偶数
$("#btn6").click(function(){
$("input[name='checkbox']:odd").attr("checked","true");
})
//反选
$("#btn4").click(function(){
$("input[name='checkbox']").each(function(){
if($(this).attr("checked"))
{
$(this).removeAttr("checked");
}
else
{
$(this).attr("checked","true");
}
})
})
//或许选择项的值
var aa="";
$("#btn5").click(function(){
$("input[name='checkbox']:checkbox:checked").each(function(){
aa+=$(this).val()
})
document.write(aa);
})
})
checkbox1
checkbox2
checkbox3
checkbox4
checkbox5
checkbox6
checkbox7
checkbox8
jquery 循环读取checkbox值
$("input[type=checkbox][checked]").each(function(){
//由于复选框一般选中的是多个,所以可以循环输出
alert($(this).val());
});
PS:上面的代码排版比较粗糙,小编这里为省事就不重新排版了,推荐几款排版工具供大家参考使用:
希望本文所述对大家jQuery程序设计有所帮助。