用PHP处理多个同名复选框
如果一个表单中有多个同名复选框,在提交到php时却只有一个值,而并不像asp那样是一串用逗号分割的值。有一个很简单的方法来解决:将复选框的name后面加上[],例如:<input type="checkbox" name="ccc" value="1"> 改为:<input type="checkbox" name="ccc[]" value="1">。这样php将得到一个叫ccc的阵列。但这种方法有个问题,如果您要在客户端对复选框是否被选择、选择了几个用javascript来判断时,javascript会因为复选框的name中含有[]而出错。您可以在表单中加入一个隐含域,用javascript设置它的值。
<script language="javascript">
function check()
{
var strchoice="";
for(var i=0;i<document.news.choice.length;i++)
{
if (document.news.choice[i].checked)
{
strchoice=strchoice+document.news.choice[i].value+",";
}
}
if (!document.news.choice.length)
{
if (document.news.choice.checked)
{
strchoice=document.news.choice[i].value;+","
}
}
strchoice=strchoice.substring(0,strchoice.length-1);
document.news.choiceid.value=strchoice;
alert(document.news.choiceall.value);
}
</script>
<html>
...
<form name="news" action="test.php" method="post" onsubmit="check()">
<input type="checkbox" name="choice" value="1">
<input type="checkbox" name="choice" value="2">
<input type="checkbox" name="choice" value="3">
<input type="checkbox" name="choice" value="4">
<input type="hidden" name="choiceid" value="">
</form>
...
</html>
<script language="javascript">
function check()
{
var strchoice="";
for(var i=0;i<document.news.choice.length;i++)
{
if (document.news.choice[i].checked)
{
strchoice=strchoice+document.news.choice[i].value+",";
}
}
if (!document.news.choice.length)
{
if (document.news.choice.checked)
{
strchoice=document.news.choice[i].value;+","
}
}
strchoice=strchoice.substring(0,strchoice.length-1);
document.news.choiceid.value=strchoice;
alert(document.news.choiceall.value);
}
</script>
<html>
...
<form name="news" action="test.php" method="post" onsubmit="check()">
<input type="checkbox" name="choice" value="1">
<input type="checkbox" name="choice" value="2">
<input type="checkbox" name="choice" value="3">
<input type="checkbox" name="choice" value="4">
<input type="hidden" name="choiceid" value="">
</form>
...
</html>