1

I have a dynamic form where user can choose the number of inputs. I don't know how many input the form could have and I'd like to store the results in an array. Here my HTML :

<select name="number-children" id="number-children">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

My jQuery :

$("#number-children").change(function () {
    var str = "";
    var count = Number($("#number-children option:selected").val());
    for (var i = 0; i < count; i++) {
      str += '<label class="col-sm-2 control-label" for="child-'+i+'">Child ' + i
              + '</label> <div class="col-sm-10"><input type="text" name="child-'+i+'" class="form-control" id="child-'+i+'"></input></div>';
   }
   $("#children").html(str);
});

How can I add each input's value into an array to collect it in a post php request ?

Thanks !

3 Answers 3

3

just Change

<input type="text" name="child-'+i+'" class="form-control" id="child-'+i+'"></input>

to

<input type="text" name="child['+i+']" class="form-control" id="child-'+i+'"></input>
Sign up to request clarification or add additional context in comments.

2 Comments

To append the answer of Abdus, you can then use $_POST['child'] as an array containing the values of i as keys, and input field values as values;
Thanks for your help, it solved my problem ! Thanks to @jeroen too !
2

Change :

 $("#children").html(str);

To :

$("#children").append(str);

1 Comment

Thanks, I'm able to send the dynamic data now !
1

The easiest way to get all children in 1 array, is to use an array in html:

str += '<label class="col-sm-2 control-label" for="child-'+i+'">Child ' + i
          + '</label> <div class="col-sm-10"><input type="text" name="child[]" class="form-control" id="child-'+i+'"></input></div>';
                                                                           ^^ here

Now when you send the form, you will have all values as an array in $_POST['child'] so you can easily loop over them regardless of the number.

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.