[英]How to get values from variable number of select elements on a form
我有一个包含稍微可变数量的select
元素的表单。 这不是用户可以选择多个选项的“多选”功能,而是可变数量的实际下拉菜单,每个菜单都有一个单选值。
问题是,并不总是知道页面上会有多少这些select
元素。 当我用PHP回显它们时,我可以给它们取一个名字,但是有没有办法用$_POST
收集它们呢? 我能想到的唯一方法是在将每个select
元素的名称回显到页面时,将它们添加到$GLOBALS
数组中。
就像是:
$GLOBALS["selectNames"] = "";
for($i = 0; $i < $number_of_selects; $i++) {
echo "<select id='select" . $i . "' name='select" . $i . "'>...</select>";
$GLOBALS["selectNames"] .= "select" . $i;
if($i < $number_of_selects - 1) {
$GLOBALS["selectNames"] .= ",";
}
}
还有其他方法吗?
您可以将它们设置为数组,并仅使用名称就可以获取所有它们:
<select name="s[]">
<option>v1</option>
</select>
<select name="s[]">
<option>t1</option>
</select>
在您的php代码中,您可以使用$_POST['s']
访问它们,这将是一个可以循环通过的数组。
foreach ($_POST['s'] as $key => $val) {
....
}
使用select
元素上的name
属性有一种很棒的方法。
在html中,使用此格式添加任意数量的选择元素
<select name='selects[1]'>
options
</select>
<select name='selects[2]'>
options
</select>
如果不需要$key
变量,可以省略数字1
和2
,如下所示。 这些值可以是您想要的任何值。 允许使用字符串。 用PHP添加select元素看起来像这样。
for($i = 0; $i < $number_of_selects; $i++) {
echo "<select id='select" . $i . "' name='select[]'>...</select>";
}
foreach ($_POST['selects'] as $key => $value) {
echo $key; // This will be the number, so 1 and then 2 ... and so on
echo $value; // This will be the value attribute for the option selected
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.