Ty Yt
Ty Yt

Reputation: 466

Store data from multiple inputs php

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 !

Upvotes: 1

Views: 72

Answers (3)

Abdus Salam
Abdus Salam

Reputation: 293

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>

Upvotes: 3

jeroen
jeroen

Reputation: 91734

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.

Upvotes: 1

Ehsan
Ehsan

Reputation: 12959

Change :

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

To :

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

Upvotes: 2

Related Questions