处理动态添加的具有相同名称的窗体控件

Handling dynamically added form controls with the same name

提问人:Madara's Ghost 提问时间:8/12/2011 更新时间:8/12/2011 访问量:478

问:

我有一个PHP循环,它输出一系列相同的表单控件(它们必须相同)。

<input type=text value="Text Here" name="text_input">
<input type=text value="Text Here" name="text_input">
<input type=text value="Text Here" name="text_input">
<input type=text value="Text Here" name="text_input">

我在CSS中使用类名和其他东西进行样式设置没有问题,但是在后端,PHP无法一次获取所有数据,因为它们都使用相同的名称。

我怎样才能使PHP能够获取和处理所有字段?我是否需要在PHP中配置一些东西,或者我缺少一个漂亮的HTML技巧?

提前致谢。

PHP 表单

评论


答:

2赞 Jonathan Kuhn 8/12/2011 #1

你可以只添加到名称的末尾,它将是 php 后端的一个数组。像这样:[]

<input type=text value="Text Here" name="text_input[]">
<input type=text value="Text Here" name="text_input[]">
<input type=text value="Text Here" name="text_input[]">
<input type=text value="Text Here" name="text_input[]">

在PHP中将是:

$_POST['text_input'][0] = ''; //whatever the first box had
$_POST['text_input'][1] = ''; //whatever the second box had
$_POST['text_input'][2] = ''; //whatever the third box had
$_POST['text_input'][3] = ''; //whatever the fourth box had

除此之外,为什么名字“必须相同”?

评论

0赞 Madara's Ghost 8/12/2011
呃,我知道有一些 HTML 技巧,它们必须相同,因为我不想处理计数器等,而且,我也在页面加载完成后在 javascript 中添加这些,所以......