1

I have a form with dynamically created input like this (simplified): I can create more people with ADD PERSON button. For each person i can add more hobbies.

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>

I'd like to post result with method POST and retrieve an array but i don't know how to index hobbies with a correct person (some person can have 0 hobbies):

Example i want:

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

var_dump($_POST["name"])

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

But with var_dump($_POST['hobby']) i get a single array like this:

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

How can I index hobbies with correct person?

1 Answer 1

1

This is achievable by adding a little more javascript to your code. The solution is to make your hobby input field name a two-dimensional array.

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

When you submit the form, use javascript logic to loop through the elements and make the first index of hobby[][] as the person name. For example, after applying JS logic, the form elements should be,

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

Now submit the form and in the PHP page, you will get this as a two-dimensional array where the first level key is the person name and their hobbies inside.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.