问题描述
我正在创建一个简单的表单来创建民意调查,因此我希望能够添加额外的输入字段,以防用户在民意调查中需要更多选项。
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.
我已经制作了向表单添加新输入字段的Javascript代码,但是在提交表单时不会发布动态添加的输入字段(我使用标准的提交按钮)。
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).
有没有办法让动态添加的字段作为表单的一部分发布/识别?
<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:
<?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>
点击添加选项两次,你得到
click Add Option twice and you get
数组([poll] =>数组([问题] => [选项1] => [选项2] => [选项3] => [选项4] =>))
Array ( [poll] => Array ( [question] => [option1] => [option2] => [option3] => [option4] => ) )
这篇关于提交使用javascript添加的表单输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!