checkbox的全选,反选,删除

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<script type=”text/javascript”>

//单项删除时的ONCLICK
function dropGet()
{
var f = confirm(“确认删除选定记录?”);
if(f)
{
return true;
}
else
{
return false;
}
}
function confirmDrop()
{
var d = false;
var items = document.getElementsByName(“a[]”);
//多项删除时,判断checkbox是否有选中项
for(var i = 0;i<items.length;i )
{
if(items[i].checked)
{
d = true;
}
}
//如果有选中项
if(d)
{
//确认删除对话框
dropGet()
}
//如果没有选中项
else
{
alert(“请选择要删除的费用记录”);
return false;
}
}
//全选
function checkedAll()
{
var items = document.getElementsByName(“a[]”);
for(var i = 0;i<items.length;i )
{
items[i].checked = true;
}
}
//反选
function checkedRev()
{
var items = document.getElementsByName(“a[]”);
for(var i = 0;i<items.length;i )
{
items[i].checked = !items[i].checked ;
}
}

</script>
</head>
<body>
<form name = “form1” id = “form1” onsubmit = “confirmDrop()”>
<input type = “checkbox” name = “a[]” id = “a” value = “1”>
<input type = “checkbox” name = “a[]” id = “a” value = “2”>
<input type = “checkbox” name = “a[]” id = “a” value = “3”>
<input type = “checkbox” name = “a[]” id = “a” value = “4”>
<input type = “checkbox” name = “a[]” id = “a” value = “5”>
<input type = “checkbox” name = “a[]” id = “a” value = “6”>
<input type = “button” onclick = “checkedAll()” value = “全选”>
<input type = “button”onclick = “checkedRev()” value = “反选”>
<input type = “submit” value = “删除”>
</form>
</body>
</html>

用document.getElementsByName()获得所有的checkbox需要每一个checkbox的名字都相同,但这会使PHP中$_POST[]接受到的checkbox值相互替换,只保存到最后一个。

解决的办法是在name后家上[] 如name = “a[]”,这样会使$_POST[“a”]作为一个数组,读取时只需要遍历$_POST[“a”]就可以了。

关于 checkbox的资料可以参考http://www.111cn.net/tags.php/checkbox