索引动态输入到其他动态输入数组

时间:2016-03-14 17:45:43

标签: javascript php

我有一个动态创建输入的表单(简化): 我可以使用ADD PERSON按钮创建更多人。 对于每个人,我可以增加更多的爱好。

的javascript:

$(document).ready(function(){

  $(".add_person").click(function(){
    var new_fieldset = $(".person:first").clone();
    $(".person:last").after(new_fieldset);
  });

  $(".add_hobby").click(function(){
    var new_input = '<input type="text" name="hobby[]" />';
    $("this").closest("fieldset").find("div_hobbies").append(new_input);
  });

});

PHP:

<fieldset class="person">
<input name="name[]" value="">
<div class="div_hobbies"></div>
<a class="add_hobby">ADD HOBBY</a>
</fieldset>

<a class="add_person">ADD PERSON</a>

我想用方法POST发布结果并检索一个数组,但我不知道如何用正确的人索引爱好(有些人可能有0个爱好):

我想要的例子:

John with hobbies "FISHING", "DIVING"
Carl with no hobbies
Eddy with hobby "SINGING"
Paul with hobbies "RUNNING", "DIVING", "CYCLING"

的var_dump($ _ POST [&#34;名称&#34;])

array(4) {
[0] => string "John",
[1] => string "Carl",
[2] => string "Eddy",
[3] => string "Paul)
}

但是使用var_dump($ _ POST [&#39; hobby&#39;])我会得到一个这样的数组:

    array(6) {
        [0] => string "FISHING",
        [1] => string "DIVING",
        [2] => string "SINGING",
        [3] => string "RUNNING",
        [4] => string "DIVING",
        [5] => string "CYCLING"
        }

如何用正确的人指出爱好?

1 个答案:

答案 0 :(得分:1)

这可以通过在代码中添加更多javascript来实现。解决方案是使您的业余爱好输入字段名称成为二维数组。

<input type="text" name="hobby[][]" />

当您提交表单时,使用javascript逻辑循环遍历元素并将hobby [] []的第一个索引作为人名。例如,在应用JS逻辑之后,表单元素应为

<input type="text" name="hobby[jack][]" />
<input type="text" name="hobby[jack][]" />
<input type="text" name="hobby[rose][]" />
<input type="text" name="hobby[rose][]" />

现在提交表单,在PHP页面中,你将把它作为一个二维数组,其中第一级键是人名和他们的爱好。

相关问题