Function that generates Multiple Inputs sends only # 1. How to solve?

1

Function creates inputs for data inclusion
By clicking add, the fields are generated correctly

The problem is that you always send # 1:
a) If you just open and click Submit;
b) even typing texts. what it sends:
field1 = 1
field2 = 1
field3 = 1 ...

How do I send the data entered in the open fields?

thank you in advance

var qtdeCampos = 0;
function addCampos() {
var objPai = document.getElementById("campoPai");
var objFilho = document.createElement("div");
objFilho.setAttribute("id","filho"+qtdeCampos);
objPai.appendChild(objFilho);
document.getElementById("filho"+qtdeCampos).innerHTML = "<input type='text' id='campo"+qtdeCampos+"' name='campo"+qtdeCampos+"' value=''>";
qtdeCampos++;
}
<!doctype html><html lang="pt-br">
<head><meta charset="UTF-8">
</head><body>
<form name="gru" method="post" action="grava.php">
<div id="campoPai"></div>
<input type="button" value="adicionar" onclick="addCampos()">
<hr><input type="submit" value="Enviar">
</form>
</body></html>
    
asked by anonymous 05.08.2018 / 01:42

1 answer

2

As I said in the comments, there is no need to create multiple id s for each element. You can use class for all, because it gets even easier then, if you want, to identify the elements by index.

Another thing, it gets trickier to get dynamically created fields with different names. It is much easier to send them as an array, and in PHP make a foreach to get the values of each index.

What you need to do is create the fields with the same name as array, adding the brackets to name :

nome="campo[]"

Your code looks like this:

function addCampos() {
   var objPai = document.getElementById("campoPai");
   var objFilho = document.createElement("div");
   objFilho.setAttribute("class","filho");
   objPai.appendChild(objFilho);
   document.querySelector("#campoPai .filho:last-child").innerHTML = "<input type='text' class='campo' name='campo[]' value=''>";
}
<form name="gru" method="post" action="teste.php">
   <div id="campoPai"></div>
   <input type="button" value="adicionar" onclick="addCampos()">
   <hr>
   <input type="submit" value="Enviar">
</form>

The "#campoPai .filho:last-child" selector will select the last div with the .filho class created.

In PHP you get the array campo with:

$campos = $_POST['campo'];

Then you can iterate the array by taking the values of each field.

Edit

Add a field limiter for a maximum of 10:

function addCampos() {

   // conta o número de campos
   var qtdeCampos = document.querySelectorAll("#campoPai .filho").length;

   if(qtdeCampos < 10){   
      var objPai = document.getElementById("campoPai");
      var objFilho = document.createElement("div");
      objFilho.setAttribute("class","filho");
      objPai.appendChild(objFilho);
      document.querySelector("#campoPai .filho:last-child").innerHTML = "<input type='text' class='campo' name='campo[]' value=''>";
   }
}
    
05.08.2018 / 02:09