haidong 发表于 2010-2-24 13:42:00

用PHP处理多个同名复选框

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