Jean Ter
Jean Ter

Reputation: 187

Get values inserted for field dynamically

I would like to insert up to 10 fields dynamically 10 into my form :

<form action="" method="post">
    ...
    <div id="dynamicInput">Entry 1
        <br>
        <input type="text" name="myInputs[]">
    </div>
    <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
     ...
    <input type="submit" class="btn btn-primary" />
 </form>

JS code :

 var counter = 1;
 var limit = 10;

 function addInput(divName) {
     if (counter == limit) {
         alert("You have reached the limit of adding " + counter + " inputs");
     } else {
         var newdiv = document.createElement('div');
         newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
         document.getElementById(divName).appendChild(newdiv);
         counter++;
     }

 }

After clicking submit in form ( with post method ) I hope to get values inserted in this field in my php page?

For example I inserted 3 values dynamically using the JS code above, so I hope to get in my php page an array like this :

Array(
    [0] => value1, [1] => value2, [2] => value3
)

Upvotes: 1

Views: 985

Answers (2)

softsdev
softsdev

Reputation: 1509

I don't know how to do with javascript but by using jquery you can do achieve it easily

please add script jquery.js in your site

HTML

<div id="dynamicInput">Entry 1
     <input type="text" name="myInputs[]" class="myInputs" />
     <input type="button" class="add_input" value="Add another text input" />
</div>

jQuery

$(document).ready(function(){
    var limit = 10;
    $(".add_input").on('click', function(){
        if( $(".myInputs").length == limit ){
            alert("You have reached the limit of adding " + limit + " inputs");
            return false;
        }
        $(".myInputs:last").after("<br>Entry "+ ( $(".myInputs").length + 1 )+" <input type='text' name='myInputs[]'  class='myInputs' />");
    });
});   

you can also check example at JSFiddle

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94672

Your initial form :

<div id="dynamicInput">Entry 1
    <br><input type="text" name="myInputs[]">
</div>

and your javascript :

var newdiv = document.createElement('div');

newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";

document.getElementById(divName).appendChild(newdiv);

Give this dynamically generate field the name name='myInputs[]'> myInputs

Therefore when you receive the forms data back into your PHP code you will receive this in the $_POST array:

$_POST['myInputs'][0] = data in the first field
$_POST['myInputs'][1] = data in the second field
$_POST['myInputs'][2] = data in the third field
...
$_POST['myInputs'][9] = data in the tenth field

Upvotes: 1

Related Questions