1

For a project, I need to generate a dynamic html form that will send POST info to a PHP page via the ACTION field.

The form has not to be static, it has to be dynamic so the user has to be able to generate(ADD) a not fixed(dynamic) number of input tags, then when all the inputs are generated and filled the user may click on submit button and send all the info to a php document via post.

I'm completely lost

I've been playing with this piece of code that generates the inputs but I'm not able to send the data via post to the php file

     <script>
var choices=[];
choices[0]="one";
choices[1]="two";

function addInput(divName){
    var newDiv=document.createElement('div');
    newDiv.innerHTML="<input type='text'>";

    newDiv.innerHTML=newDiv.innerHTML+"</input>";
    document.getElementById(divName).appendChild(newDiv);
}
</script>
<form class="new" method="post" action="action.php">
    <div id="dynamicInput">
    </div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />

</form>
user3166611
  • 61
  • 3
  • 8

2 Answers2

0

just change your input type to submit instead of save

<input type="submit" value="Save" />

and you don't need to create new div each time to create an input you can either append it to the div you already have

document.getElementById(divName).innerHTML+= "<input type='text' name= 'added_input[]'/>";

or

var newInput=document.createElement('input');
// if you want each input in separate lines
newInput.style.display = "block";
newInput.setAttribute("name","added_input[]");
document.getElementById(divName).appendChild(newInput);

and in your php file you can get post values like this :

for ($i = 0; $i < $_POST['added_input']; $i++){
   echo $_POST['added_input'][$i];
}

for more option to get post values see This Question

Community
  • 1
  • 1
Aya Salama
  • 1,458
  • 13
  • 17
0
  1. To submit the form, one possible scenario is to change the type of Save button to submit:
    <input type="submit" value="Save" />
  2. Also add name property to your auto generated inputs. Otherwise you won't access the submitted $_POST data:
    <input name="enter_name[]" type='text'>
  3. As you see, I'm concatenating [] to the input field. That will convert all submitted data into an array. Otherwise, that last one auto generated input will overwrite the previous entered data.
Jordan Enev
  • 16,904
  • 3
  • 42
  • 67