Add and subtract values from multiple input's after they have been created or removed with appendChild and removeChild.

2

Well my problem is as follows, with the appendChild of JavaScript I create an input with value X with its own ID but it can be random, and I add another with the same method with the same situation as the other but with a different value (Leading on account that X is a numeric value) well, my problem is that I do not know how I will add or subtract those input's having random id's as they are created or removed. I'm grateful if you can help me. Here is the code I use to create:

function adicionar(conteudo) {
  var node = document.createElement("input");
  dados = conteudo.split('|'); //separa a id do valor e cria um array nos dados
  node.setAttribute("id", dados[0]); //insere a id
  node.setAttribute("type", "text"); //insere o tipo
  node.setAttribute("value", dados[1]); //insere o valor
  document.getElementById("lista").appendChild(node); //escreve na div
}
<div id="lista"></div>
<!--a esquerda a id a direia o valor-->
<button onclick="adicionar('1|5');">adicionar input 1</button>
<button onclick="adicionar('2|7');">adicionar imput 2</button>
    
asked by anonymous 11.06.2018 / 00:11

1 answer

1

In this way you are inserting fields with id s equal ( 1 or 2 ).

Generate% with only% s counting the number of fields. And do not just use a number like id , include a string together. In my example below, I am generating id s: id , campo0 , campo1 etc ..

function adicionar(conteudo) {
  var node = document.createElement("input");
  var novo_id = document.querySelectorAll("#lista input").length;
  node.setAttribute("id", "campo"+novo_id); //insere o id
  node.setAttribute("type", "text"); //insere o tipo
  node.setAttribute("value", conteudo); //insere o valor
  document.getElementById("lista").appendChild(node); //escreve na div
}
<div id="lista"></div>
<button onclick="adicionar('5');">adicionar input 1</button>
<button onclick="adicionar('7');">adicionar imput 2</button>

To add or subtract you can pick up two or more fields by their campo2 . Or if you use all, you can select all at once with id and loop document.querySelectorAll("#lista input") :

function somarTudo(){
   var campos = document.querySelectorAll("#lista input");
   var soma = 0;
   for(var x=0; x<campos.length; x++){
       soma += parseInt(campos[x].value);
   }

   return soma;
}

To get the summed values, just call the function for .

    
11.06.2018 / 01:49