---
title: "判断checkbox选中的个数"
author: "mywebcode"
date: "2013-11-14T15:08:00Z"
tags: []
slug: "checkbox"
draft: false
lastmod: "2014-04-30T09:16:49Z"
id: 2058361
url: "https://mywebcode.iteye.com/blog/2058361"
---

直接看例子吧：shippingAddressList 为一个集合

&lt;c:forEach items="${shippingAddressList }" var="var"&gt;

&lt;tr&gt;  
&lt;td align="right"&gt;&lt;input type="checkbox" value="${var.id }" name="checked"&gt; &lt;/td&gt;  
&lt;td&gt;${var.contact }&lt;/td&gt;  
&lt;td&gt;${var.phone}&lt;/td&gt;  
&lt;td&gt;${var.postalCode }&lt;/td&gt;  
&lt;td align="left"&gt;${var.address }&lt;/td&gt;  
&lt;/tr&gt;

&lt;/c:forEach&gt;

//forEach循环遍历出所有的checkbox 他们具有相同的name

var i=0;

var items = document.getElementsByName("checked"); //这个语句帮我们筛选出一组name为checked的复选框。。

for(var j=0; j&lt;items.length; j++){

if(items\[j].checked){ //如果该复选框被选中

i++; //统计被选中的个数

}

}

$("\[name='checkbox']").attr("checked",'true');//全选

$("\[name='checkbox']").removeAttr("checked");//取消全选

$("\[name='checkbox']:even").attr("checked",'true');//选中所有奇数

//反选

$("\[name='checkbox']").each(function(){  
if($(this).attr("checked"))  
{  
$(this).removeAttr("checked");  
}  
else  
{  
$(this).attr("checked",'true');  
}

//判断某个复选框是否被选中

有这样一个复选框&lt;span style="margin-left: 20px;"&gt;&lt;input type="checkbox"id="agree"&gt;我已阅读并同意&lt;/span&gt;

在js中我们去判断其是否被选中

alert($("#agree").is(":checked")) 如果被选中 弹出 true 反之 false