添加多个字段以形成 [英] Add multiple fields to form
问题描述
我想添加一个为我的表单生成多个字段的函数。
I would like to add a function that generates multiple fields to my form.
这就是我的表单的样子:
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
在我的情况下,我想要点击添加更多时需要3个新字段(姓名,电话,电子邮件)字段。
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
我该怎么做?
https://jsfiddle.net/374cxt5s/
推荐答案
试试这个: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
这允许您在提交表单时将结果存储在数组中。由于您可以拥有5个姓名,电话和电子邮件,因此数组是解决此问题的最佳方式。然后在PHP中,你将 $ _ POST ['name'] [0]
作为第一个。
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0]
as the first one.
这篇关于添加多个字段以形成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!