Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  139] [ 2]  / answers: 1 / hits: 45495  / 9 Years ago, wed, december 30, 2015, 12:00:00

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>


In my case I want 3 new fields (name, phone, email) when clicking on Add more fields.



How can I do this?



https://jsfiddle.net/374cxt5s/


More From » jquery

 Answers
4

Try this: 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>&nbsp;</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>);
});
});


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.


[#63891] Monday, December 28, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ishmaelw

Total Points: 528
Total Questions: 96
Total Answers: 103

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
ishmaelw questions
;