Problem in Adding Multiple Inputs

Asked

Viewed 39 times

0

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); }
  • 3

    Why did you initialize soma with an array? It should not have initialized with 0?

  • Also, where did the variable come from nacional?

1 answer

2


Some problems to take into account:

  • []is an array, to join items/values, you must use a number to add.
  • parseInt should be used with Radix, i.e. 10 as second argument. I prefer to use Number().

An example of what you want to do:

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

function somatoriaNacional(inputs) {
  return [...inputs].reduce((soma, input) => soma + Number(input.value), 0);
}

var somaNacional = somatoriaNacional(nacional);
console.log('Soma:', somaNacional);
<form class="nacional">
  <input class="soma-nacional" value="5">
  <input class="soma-nacional" value="3">
  <input class="soma-nacional" value="2">
</form>

Your corrected code would be like this:

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



function somatoriaNacional() {
  var soma = 0;

  for (var i = 0; i < nacional.length; i++) {
    soma += Number(nacional[i].value);
  }
  return soma;
}

var somaNacional = somatoriaNacional(nacional);
console.log('Soma:', somaNacional);
<form class="nacional">
  <input class="soma-nacional" value="5">
  <input class="soma-nacional" value="3">
  <input class="soma-nacional" value="2">
</form>

Browser other questions tagged

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