3
var quant = document.getElementsByName("valor[]");
var teste = [];
function somarValores(){
var soma = 0;
for (var i=0; i<quant.length; i++){
teste[i] = quant[i].value;
soma += teste[i];
}
document.getElementById("resultado").innerHTML = soma;
}
<label>Valor 1:</label>
<input name="valor[]" type="number"/>
<label>Valor 2: </label>
<input name="valor[]" type="number"/>
<label>Valor 03: </label>
<input name="valor[]" type="number"/>
<label>Valor 04: </label>
<input name="valor[]" type="number"/>
<input type="button" onClick="somarValores()" value="botao">
<p id="resultado"></p>
I’m trying to add a javascript array and return the total, but it just shows me the array, no sum...?
Hello, when I put parseint, it recognizes all fields as Nan, and if any of them are not filled in, the sum does not occur.
– Rocha
@Rock makes sense. You can use
parseInt(el.value, 10) || 0;
for it to use zero if there is no value in the input. I added iso in the answer as well.– Sergio