Dynamic Form Fields
Scale your forms. This script demonstrates how to use `document.createElement` and `appendChild` to let users generate as many input fields as they require.
Copy the Script
<div id="container">
<input type="text" name="items[]">
</div>
<button onclick="add()">Add</button>
<script>
function add() {
var input = document.createElement("input");
input.type = "text";
input.name = "items[]";
input.style.display = "block";
input.style.marginTop = "5px";
document.getElementById("container").appendChild(input);
}
</script>
Frequently Asked Questions
If you name the inputs as an array (e.g., `name='guest[]'`), PHP will automatically receive them as an array of values when the form is submitted.
Yes. You can add a counter variable and check `if (count < max)` before appending a new child element.
Yes. When creating the new input, you can also append a 'Remove' button that calls `parent.remove()` on the container div.