I’m making a simple form to create polls, therefore I want the possibility to add additional input fields in case the user wants more options in the poll.
I’ve made Javascript code that adds a new input field to the form, but the dynamically added input fields are not posted when the form is submitted (I use a standard submit button).
Is there some way to get the dynamically added fields posted/recognized as a part of the form?
<form id='myForm' method='post'> <input type='submit'> <input type='text' name='poll[question]'> <input type='text' name='poll[option1]'> <input type='text' name='poll[option2]'> </form> <a href='javascript:addOption();'>Add option</a> <script> var optionNumber = 3; //The first option to be added is number 3 function addOption() { var theForm = document.getElementById('myForm'); var newOption = document.createElement('input'); newOption.name = 'poll[option'+optionNumber+']'; // poll[optionX] newOption.type = 'text'; theForm.appendChild(newOption); optionNumber++; } </script>
Your code works fine as is:
click Add Option twice and you get
Array ( [poll] => Array ( [question] => [option1] => [option2] => [option3] => [option4] => ) )