Boot / add-in function dynamically deleting previously added input values

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 bottom of the page.

The function works perfectly when it comes to adding div and textboxes,  but when I click the button again and one of the textboxes added previously is already filled, what is written goes out and it goes blank.

I have no idea why this occurs, I thought it was because the names of the textboxes are arranged as an array, but it looks like 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>";


}
    
asked by anonymous 12.12.2014 / 01:05

1 answer

2

There are some things wrong with your code. Here's the fix:

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);

}

Do not change innerHMTL otherwise the browser will throw away the previous elements and what was filled, and recreate everything again.

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

    
12.12.2014 / 03:14