I changed my code to the following:
$(document).ready(function () {
$('#add').on('click', function () {
var $contacts = $(".contact");
$("<div/>").append($("<input>", {
"type": "text",
"name": "contact[" + $contacts.length + "][name]"
})).insertAfter($contacts.last());
});
});
<div class="contact">
Name: <input type="contact[0][name] type="text">
</div>
<div class="contact">
Name: <input type="contact[1][name] type="text">
</div>
<div class="contact">
Name: <input type="contact[2][name] type="text">
</div>
This works and allows me to add another row. However, I need help on two things:
1) When I add another row and hit submit. The $_POST array only shows the first three values, not the dynamically added arrays.
2) How do I add more the text to the appended html? It only shows the input box, not “Name: ” in front of it.
Thanks!
This is what print_r($_POST) is returning (I have other form fields in there):
Post:
Array
(
[custsubmit] => Submit
[contact] => Array
(
[0] => Array
(
[id] =>
[name] => name1
)
[1] => Array
(
[id] =>
[name] => name2
)
[2] => Array
(
[id] =>
[name] => name3
)
)
)
You can start by using a multidimensional array.
I changed the
idof your<div>container to a classname since theidattribute is meant to be unique.Now, to add a new row you can use something as follows.
This way, you will receive a nice array in PHP to work with which will look like this:
You can use more complicated layout by making use of a DOM template as I previously answered here.
You can see it here.