document.addEventListener("DOMContentLoaded", function () {
var form = document.querySelector("form");
var formContainer = document.querySelector('#container');
document.getElementById("newPlace").addEventListener("click", cloneSection);
form.addEventListener("click", function (evt) {
if (evt.target.name == "remove")
formContainer.removeChild(sectionFor(evt.target));
});
form.addEventListener("input", function (evt) {
if (evt.target.name == "uberschrift")
updateHeader(sectionFor(evt.target), evt.target.value);
});
function cloneSection(evt) {
var target = form.querySelector("#container section:first-child").cloneNode(true);
formContainer.appendChild(target);
updateHeader(target, null);
var textFields = target.querySelectorAll("input[type=text]");
for (j = 0; j < textFields.length; ++j)
textFields[j].value = '';
}
function updateHeader(section, hdrValue) {
var header = section && section.querySelector("h2 span");
if (hdrValue != null)
header.innerText = " - " + hdrValue;
else
header.innerText = "";
}
function sectionFor(control) {
while (control && control.tagName.toLowerCase() != "section")
control = control.parentNode;
return control;
}
});
<form name="form1" action="index.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="container" style="display: block;">
<section>
<h2>Place <span></span><button id="remove" type="button" name="remove">Delete</button></h2>
<label for="headline"><span>Headline:</span><input type="text" name="headline" size="80"></label>
</section>
</div>
<!--</form>-->
<button id="newPlace" type="button">New Headline</button>
<input type="hidden" name="aktion" value="save">
<button id="enter" type="submit" value="save">Submit</button>
</form>
I wrote a dynamic form where you can add form fields with a button. Now I am trying to save them into mysql database, but it only takes the last value of my input fields which are generated. I figured out, it's because of the name which is still in every created field is still the same. How can I solve this with pure JS? I was thinking about to use something like a loop and simply increment it then.
<form name="form1" action="index.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div id="container" style="display: block;">
<label for="headling"><span>Headline:</span><input type="text" name="headline" size="80"></label></div>
Thanks in advance!