几个共享相同名称的复选框

Buz*_*uzu 12 html php forms checkboxlist

根据w3c"表单中的几个复选框可以共享相同的控件名称.因此,例如,复选框允许用户为同一属性选择多个值." 但是,如果这样做,PHP将只采用最后一个值.例如:

<?php
if ($_POST) {
echo "<pre>";
print_R($_POST);
echo "</pre>";
}
?>
<form action="" method = "post">
<input type="checkbox" name="pet" value="dog" />Dog<br />
<input type="checkbox" name="pet" value="Cat" />Cat<br />
<input type="checkbox" name="pet" value="bird" />bird<br />
<input type="checkbox" name="pet" value="iguana" />iguana<br />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

如果您提交该表单,您将看到只会设置最后一个显示的复选框.浏览器将它们全部发送,但它们会相互覆盖.因此,将相同名称设置为多个复选框可能会导致问题.它总是这样吗?我似乎记得实际上可以将所有值作为数组发送.

我知道你可以在名称的末尾添加一个[]来创建一个值数组:

<?php
if ($_POST) {
echo "<pre>";
print_R($_POST);
echo "</pre>";
}
?>
<form action="" method = "post">
<input type="checkbox" name="pet[]" value="dog" />Dog<br />
<input type="checkbox" name="pet[]" value="Cat" />Cat<br />
<input type="checkbox" name="pet[]" value="bird" />bird<br />
<input type="checkbox" name="pet[]" value="iguana" />iguana<br />
<input type="submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

但是w3c没有具体说明.老实说,我不记得我是否总是使用名称末尾的[],但出于某种原因,我认为在某些时候我没有.过去有没有时间可以让你在没有[]的情况下工作?

http://www.w3.org/TR/html401/interact/forms.html#checkbox

sou*_*edi 6

如果没有[]PHP,那将永远不会有效.

W3C没有指定有关如何在服务器端处理查询字符串的任何内容.(忽略CGI规范中一个不相关的,过时的角落,只与PHP有关,因为直到最近它才是安全漏洞).

由于您描述的原因,看起来该模式是有效标记,但不常用.

一个类似的模式用于无线电按钮,其中只有一个可在一个时间被选择.(事实上​​,给无线电输入相同的名称是浏览器如何将它们视为一个组).也许这就是你的想法.