【问题标题】:Multiple form with same name array具有相同名称数组的多个表单
【发布时间】:2017-07-29 07:20:07
【问题描述】:

我有 2 个这样的表格:

表格一:

<input type="text" name='name[]' placeholder = 'Input your name' >
<input type="text" name='vehicles[]' placeholder = 'Input your first vehicle'>
<input type="text" name='vehicles[]' placeholder = 'Input your second vehicle'>
....
<input type="text" name='vehicles[]' placeholder = 'Input your xxx vehicle'>

表格2:

<input type="text" name='name[]' placeholder = 'Input your name' >
<input type="text" name='vehicles[]' placeholder = 'Input your first vehicle'>
<input type="text" name='vehicles[]' placeholder = 'Input your second vehicle'>
....
<input type="text" name='vehicles[]' placeholder = 'Input your xxx vehicle'>

车辆输入是JavaScript添加的动态输入,那么如何识别正确的人拥有的车辆呢?我已经检索到数据,但我不知道如何按每个人划分车辆。

【问题讨论】:

  • 您需要在每个输入字段中指定不同的名称以保存所有输入值。
  • 所以每个表单都有不同的名称?
  • 所有输入都是单一形式还是多重形式?
  • 比如vehicles1[],vehicles2[],vehicles3[]等等..
  • 单一表格,表格的数量也是动态的,所以可能会有人3的追加表格,直到人n

标签: php input request


【解决方案1】:

我已经为您的车辆领域实施了一个解决方案,希望您能够修改此代码以满足您的需求。

使用 JavaScript 创建名称时,在名称末尾添加一个数字,即:

var counter = 0;
function addInput() {
    document.getElementById("form").insertAdjacentHTML("beforeend", "<input type=\"text\" name=\"vehicles"+counter+"\" placeholder=\"Input vehicle #"+counter+"\">");
    counter++;
}

然后,在 PHP 中,您可以简单地获取通过 $_POST 发送的所有项目的列表:

$vehicles = array_keys($_POST); //Get all of the $_POST values
for ($i=0;$i<count($vehicles);$i++) { //Loop through all $_POST values
    if (strpos($vehicles[$i], "vehicles")!==false) { //If the name contains "vehicles"
        $value = $_POST[$vehicles[$i]]; //Get the value of the field
        echo $i . " " . $value . "<br>"; //Echo it out as a test
    }
}

【讨论】:

    【解决方案2】:

    您可以不为每个附加表单创建带有 name[]vehicles[] 名称的输入,而是将输入包装在用户(或您想要的任何其他名称)数组中并执行类似 users[].name[]users[].vehicles[] 的操作。(我不确定正确的语法,但事情是包装它)

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多