<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<style type="text/css">
.form1 {
width:300px;
margin:30px;
}
</style>
<script language="javascript">
$(function(){
//全选
$("#selectAll").click(function(){
$("[name=items]:checkbox").attr("checked",this.checked);
});
//当选项全部选中时,全选也选中
$tem = $("[name=items]:checkbox");
$("[name=items]:checkbox").click(function(){
$("#selectAll").attr("checked",$tem.length==$tem.filter(":checked").length);
/*
更简洁写法如下,但不容易理解,解释下$("[name=items]:checkbox").filter(":not(:checked)").length是指未被选中的个数,!即取反,
当未被选中的个数为0时,!0即为true,所以全选的复选框为选中状态;
当未被选中的个数为n(n>0)时,!n即为false,所以全选的复选框为未选中状态 */
//$("#selectAll").attr("checked",!$("[name=items]:checkbox").filter(":not(:checked)").length);
});
})
</script>
</head>
<body>
<form class="form1">
<fieldset>
<legend>喜爱的水果</legend>
<div>
<input id="selectAll" type="checkbox"/>
<label for="selectAll">全选</label>
</div>
<div>
<input name="items" type="checkbox" value="苹果"/>
<label >苹果</label>
</div>
<div>
<input name="items" type="checkbox" value="香蕉"/>
<label >香蕉</label>
</div>
<div>
<input name="items" type="checkbox" value="李子"/>
<label >李子</label>
</div>
<div>
<input name="items" type="checkbox" value="雪梨"/>
<label >雪梨</label>
</div>
</fieldset>
</form>
</body>
</html>