Mateo Villagomez Mateo Villagomez - 6 months ago 20
HTML Question

Submission form with input duplicates

I have a button that duplicates two inputs with their own id (i++ and r++ from original). When I submit the form and run:

foreach ($_POST as $id => $value) {
echo $value;

process.php page doesn't recognise the new inputs $id or $value.

The duplication code is the following:

document.getElementById('button').onclick = duplicate
var i = 0;
var r = 0;
var items = document.getElementById('items');
var cantidad = document.getElementById('cantidad');
function duplicate() {
var cloneitems = items.cloneNode(false); // "deep" clone = "items" + ++r; // there can only be one element with an ID
var cloneCantidad = cantidad.cloneNode(false); // "deep" clone = "cantidad" + ++i; // there can only be one element with an ID

My html:

<form method="post" action="process.php" enctype="multipart/form-data">
<h4 class="input-margin">Items<button type="button" id="button" onclick="duplicate()" class="btn btn-primary margin-left input-margin">+</button></h4>
<div class="input-margin">
<div class="col-xs-12 col-sm-6">
// First duplicated input
<select class="input-margin form-control" id="items" placeholder="Nombre" name="item" data-style="btn-primary">
<?php while($row = mysqli_fetch_array($itemResults)) : ?>
<option><?php echo $row['item']; ?></option>
<?php endwhile; ?>
<div class="col-xs-12 col-sm-6">
// Second duplicated input
<input type="number" class="input-margin form-control txtboxToFilter" id="cantidad" placeholder="Cantidad" name="cantidad" min="1">
<div class="col-xs-12 col-sm-12 submit-button">
<button type="submit" class="btn btn-primary btn-block" name="submit" value="ingreso">Ingresar</button>

The user must have the possibility to use as many duplications as they want. Each of them will have different inputs, thats why I need unique ids to make changes in mysql.

Why is the new id not being showed or recognise, and is there any better way to get all the values from the duplicated inputs?


Form fields are posted with their names, not their ID. So each of the appended input will overwrite the others. Differentiate the name and you will get each. Or you can give these input an array as name: name="cantitad[]" and you will get one array with all the values.