Button/function to add inputs dynamically by deleting values from previously added inputs

Asked

Viewed 827 times

3

I made a form where a button calls the function "addproduct()" in this function I create 1 div and 2 textbox that are placed in the same div, and then add the div to a span at the end of the page.

The function works perfectly when it comes to adding the div and the textboxes, only when I click the button again and one of the previously added textboxes is already filled, the written one erases and it is empty.

I have no idea why this occurred, I thought it was because the "Names" of the textboxs were organized as an array, but it seems that it is not. here is the code:

var contador = 1;
function addproduto() 
{
var div = document.createElement("div");
contador = contador + 1;
var nome = document.createElement("input");
var qtd = document.createElement("input")
div.setAttribute("id", contador);

nome.setAttribute("type", "text");
nome.setAttribute("name", "nome[]");

qtd.setAttribute("type", "text");
qtd.setAttribute("name", "qtdprod[]");

var spanlugar = document.getElementById("lugar");

    //coloca os elementos no ultimo lugar da nova div e entre eles os textos
    div.innerHTML = div.innerHTML + "Nome do produto " + contador  + ":" ;
    div.appendChild(nome);
    div.innerHTML = div.innerHTML + "<br> Quantidade:";
    div.appendChild(qtd);

//colca o div no ultimo lugar do span.
  spanlugar.appendChild(div);
 spanlugar.innerHTML = spanlugar.innerHTML + "<br>";


}
  • They could post the form code as well?

1 answer

2

There are some things wrong with your code. Follows the correction:

var contador = 1;
function addproduto() 
{
  contador++;

  var _div = document.createElement("div");
  var _nome = document.createElement("input");
  var _qtd = document.createElement("input")
  var _br01 = document.createElement("br")
  var _br02 = document.createElement("br")

  var _divInfo01 = document.createTextNode("Nome do produto " + contador  + ":");
  var _divInfo02 = document.createTextNode("Quantidade:");

  _div.setAttribute("id", contador);

  _nome.setAttribute("type", "text");
  _nome.setAttribute("name", "nome[]");

  _qtd.setAttribute("type", "text");
  _qtd.setAttribute("name", "qtdprod[]");

  var spanlugar = document.getElementById("lugar");

  //coloca os elementos no ultimo lugar da nova div e entre eles os textos
  _div.appendChild(_divInfo01);
  _div.appendChild(_nome);
  _div.appendChild(_br01);
  _div.appendChild(_divInfo02);
  _div.appendChild(_qtd);

  //colca o div no ultimo lugar do span.
  spanlugar.appendChild(_div);
  spanlugar.appendChild(_br02);

}

Don’t change the innerHMTL otherwise the browser will throw out the previous elements and the one that was filled, and recreate everything again.

Also, to create text, use the above method to create text "nodes".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.