我正在做一个简单的表单来创建民意测验,因此我想要添加额外的输入字段,以防用户在轮询中想要更多的选项.
我已经创建了JavaScript代码,为表单添加了一个新的输入字段,但是当表单提交时,动态添加的输入字段不会被发布(我使用标准的提交按钮).
<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>
解决方法
你的代码工作正常:
<?PHP print_r($_REQUEST) ?> <html> <body> <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> </body> </html>
单击添加选项两次并得到
Array([poll] => Array([question] => [option1] => [option2] => [option3] => [option4] =>))