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] => ) )
I just debugged my site where I was having a similar issue. For me it turned out that having my table and form tags in the "wrong" order caused the issue.
Broken:
Working:
This points out something pretty important. The browser may render fine, and the form may work fine, with malformed html, but you can still break things, like this, by having not having properly formatted html. Maybe I should start using mod_tidy!
Are you sure you are not making any mistake here ?
I copied your code in a new page and added the following to the code behind of an ASP.NET page (it should work on any framework):
I added additional fields and entered test values, the output clearly shows all dynamic input fields posted back to the server.
Here is the output:
You can always serialize the form yourself using a javascript function and then submit that (using AJAX or a get request or something).
http://malsup.com/jquery/form/comp/