Sum several inputs

Asked

Viewed 39 times

-1

Would you be so kind as to help me?

I’m trying to make a function that adds up several inputs, but instead of adding it is concatenating.

HMTL

<form class="nacional">
    <input class="soma-nacional" value="5">
    <input class="soma-nacional" value="3">
    <input class="soma-nacional" value="2">
</form>

JS

var nacional = document.querySelectorAll(".soma-nacional");
var somaNacional = [];

function somatoriaNacional(){
    var soma = [];

    for(var i = 0; i < nacional.length; i++){
        soma += parseInt(nacional[i].value);
    }
    console.log(soma); 
}

1 answer

1

The problem is that you initialized the variable soma with a array, when you should initialize with a number (in this case the number zero). See below for what your code should look like:

function somatoriaNacional(){
    var soma = 0;

    for(var i = 0; i < nacional.length; i++){
        soma += parseInt(nacional[i].value);
    }
    console.log(soma); 
}

Browser other questions tagged

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