Sum Javascript Array

Asked

Viewed 22,787 times

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...?

4 answers

2


You have to use .parseInt() to convert from Type string for Type number.

When you have quant[i].value this will return text, not a number. So you have to convert for example "10" for 10.

If you check you’ll see that typeof quant[i].value will give "string" and not "number".

Use then:

teste[i] = parseInt(quant[i].value, 10);     

var quant = document.getElementsByName("valor[]");
var teste = [];

function somarValores(){
var soma = 0;

 
for (var i=0; i<quant.length; i++){
   		teste[i] = parseInt(quant[i].value, 10) || 0;      
        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>

You can also use the .reduce() instead of the cycle for.
Then I’d be like this:

function somarValores() {
    var soma = [].reduce.call(quant, function (somatorio, el) {
        return somatorio + parseInt(el.value, 10) || 0;
    }, 0);
    document.getElementById("resultado").innerHTML = soma;
}

jsFiddle: http://jsfiddle.net/yuqfgga2/1

  • 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.

  • @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.

1

Test this out here: If you add parseint() in test[i] solves your problem.

var quant = document.getElementsByName("valor[]");
var teste = [];

function somarValores(){
var soma = 0;

 
for (var i=0; i<quant.length; i++){
  
   		teste[i] = parseInt(quant[i].value);      
        soma += parseInt(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>

-2

    <div class="container">
        <div class="row">
            <div class="form-group col-md-3">
                <label>Produto</label>
                <input type="text" name="descricao_produto[]" id="descricao_produto" class="form-control">
            </div>
            <div class="form-group col-md-3">
                <label>Valor do Produto</label>
                <input type="number" name="valor_produto[]" id="valor_produto[]" class="form-control">
            </div>
            <div class="form-group col-md-2">
                <label>Quantidade</label>
                <input type="number" name="quantidade_produto[]" id="quantidade_produto[]" class="form-control">
            </div>
            <div class="form-group col-md-3">
                <label>Total Produto</label>
                <input type="number" class="form-control" name="produto_valor[]" id="produto_valor[]">

            </div>

            <div class="form-group col-md-1">

                <a class="btn btn-warning" id="produto_adiciona" >+</a>
            </div>
        </div>
<div id="produto_adicionado"></div>
        <div class="row">
            <div class="col-md-4">
            <p id="resultado"></p>
        </div>
        </div>
       <div class="row">
        <div class="form-group col-md-3">
         <input type="submit" class="btn btn-success" onclick="somarValores()">
       </div>
    </div>
    </div>
<!-- Javascript ---> 
<script type="text/javascript">

    $( "#produto_adiciona" ).click(function() {
  $( "#produto_adicionado" ).append( "<div class='row'><div class='form-group col-md-4'><input type='text' class='form-control' name='produto_valor[]'></div><div class='form-group col-md-1'><button class='btn btn-warning' id='produto_adiciona'>+</button>          </div></div>" );s
});



var quant = document.getElementsByName("produto_valor[]");
var teste = [];

function somarValores(){
var soma = 0;


for (var i=0; i<quant.length; i++){

        teste[i] = parseInt(quant[i].value);      
        soma += parseInt(teste[i]);
 }  
  document.getElementById("resultado").innerHTML = soma;
}
  • Do not answer only with code. Explain what your answer is intended to do so that it is easy for any reader to follow. Regarding the code it also not only did not get properly formatted as it seems to have gotten some more lost things as for example $( "#produto_adicionado" ).append( "+ " );s });

-2

var array = ["1", "2", "3"]; // example of a basic array!

var sum = 0;

for (var x=0; x < array.length; x++) {

 soma += parseInt(array[x]);

}

// sum equals: 6

Browser other questions tagged

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