【问题标题】:Post form inputs as seperate arrays将表单输入作为单独的数组发布
【发布时间】:2017-12-02 10:59:36
【问题描述】:

我需要通过表单发布任意数量的“行”数据,以实现以下数组结构,这样impact_speed 将包含 x 个数组,每个数组都包含一个 @987654322 @、valueunit 元素:

array(1) {
  ["impact_speed"]=>
  array(3) {
    [0]=>
    array(3) {
      ["description"]=>
      string(3) "one"
      ["value"]=>
      string(2) "10"
      ["unit"]=>
      string(3) "mph"
    }
    [1]=>
    array(3) {
      ["description"]=>
      string(3) "two"
      ["value"]=>
      string(2) "20"
      ["unit"]=>
      string(3) "kph"
    }
    [2]=>
    array(3) {
      ["description"]=>
      string(5) "three"
      ["value"]=>
      string(2) "30"
      ["unit"]=>
      string(3) "fps"
    }
  }
}

如果行数是固定的,我可以通过像这样索引表单输入来实现这一点:

<input type="text" name="impact_speed[0][description]" value="one">
<input type="text" name="impact_speed[0][value]" value="10">
<input type="text" name="impact_speed[0][unit]" value="mph">

<input type="text" name="impact_speed[1][description]" value="two">
<input type="text" name="impact_speed[1][value]" value="20">
<input type="text" name="impact_speed[1][unit]" value="kph">

<input type="text" name="impact_speed[2][description]" value="three">
<input type="text" name="impact_speed[2][value]" value="30">
<input type="text" name="impact_speed[2][unit]" value="fps">

但是,我使用 javascript UI 添加这些内容,允许用户单击加号图标来创建新行,因此我没有固定数量的行可供使用。

例如,如果我没有像下面的例子那样指定索引号,它显然会为每行创建三个单独的数组,这不是我想要的:

<input type="text" name="impact_speed[][description]" value="three">
<input type="text" name="impact_speed[][value]" value="30">
<input type="text" name="impact_speed[][unit]" value="fps">

有没有一种方法可以命名我的表单输入,而不必动态插入索引号(0、1、2 等)?

【问题讨论】:

  • 你的 Javascript 是什么样的?

标签: html arrays forms


【解决方案1】:

我最终索引了我的数组,因为我意识到这是唯一可行的方法。然后,每次添加一行时我都会增加索引。这是克隆行后用于增加索引的代码示例。

// If the input names contain an array index, we need to increment it:
$newRow.find('input, select').each(function(){
  $(this).attr('name', $(this).attr('name').replace(/\[([0-9]+)\]/, function(match, capture) {
    return '[' + (parseInt(capture, 10) + 1) + ']' ; 
  }));
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2011-11-29
    • 1970-01-01
    相关资源
    最近更新 更多