The most appropriate would be to use the method createElement
(dynamically create an element). This is because using innerHTML
, the values typed in all fields will be deleted. Now, to make the procedure easier, create a span
with a id
where the new fields will be inserted:
<span id="valores">
valor 2: <input type="text" name="valor2" />
</span>
The span
is useful in such cases because it serves as a reference container and does not affect the layout.
See how it would look (explanatory comments in the code):
var botao = document.getElementById("btn");
botao.addEventListener('click', function() {
// pega a span pelo id
var vals = document.getElementById("valores");
// cria a tag <br>
var br = document.createElement("br");
// insere no span
vals.appendChild(br);
// pega todos os inputs dentro do span
var qtd = document.querySelectorAll("#valores input");
// como já tem um, soma com 2 para criar uma contagem sequencial
var names = qtd.length + 2;
// cria o nó de texto
var lab = document.createTextNode("Valor "+ names +": ");
// insere no span
vals.appendChild(lab);
// cria o input
var inp = document.createElement("input");
// cria atributo "type"
inp.type = "text";
// cria atributo "name" com o valor sequencial
inp.name = "valor"+names;
// insere no span
vals.appendChild(inp);
});
Valor do produto:<input type="text" name="valor1" />
<br />
<span id="valores">
valor 2: <input type="text" name="valor2" value="10,20" />
</span>
<br />
valor final: <input type="text" name="valor final" />
<br/>
<button id="btn">Adicionar novo valor</button>
And If the guy clicks 10x gets 10 equal Abels? What will be on this label?
– hugocsl
are basically are the same and with label I refer to inputs, but the idea is that they have different values, as they will be added at the end, because of this they need to have different names or ids, but this I arrange later
– informatiza