How do I get the value with getElement and assign it to a variable?

5

I have this code where I'm getting the values correctly from the form (I made a alert with each item and it's getting right). But when saving the variable the sum is not right, when I give alert in sum it appears NaN . Here's the snippet of my code:

function somaPesos() {
    var soma = 0;
    var itens = document.getElementsByClassName("soma");

    for (i = 0; i < itens.length; i++) {
        var item = parseInt(itens[i].value);
        alert(item);
        soma = soma + item;
    }

    alert(soma);    
    return false;
}
    
asked by anonymous 17.11.2014 / 11:38

4 answers

4

This error is probably occurring because some input that contains the "sum" class is worthless. You can do a check before, so it does not occur anymore.

function somaPesos() {
  var soma = 0;
  var itens = document.getElementsByClassName("soma");

  for (i = 0; i < itens.length; i++) {
    if (!isNaN(parseInt(itens[i].value))) {
      var item = parseInt(itens[i].value);
      soma += item;
    }
  }

  alert(soma);
  return false;
}
Valor 1: <input type="text" class="soma"><br>
Valor 2: <input type="text" class="soma"><br>
Valor 3: <input type="text" class="soma">
<input type="button" onclick="somaPesos()" value="Somar">

What I did was give a parse to Int in the input, because empty the function IsNaN returns false and then I denied for it and enter and assign the value to sum.

    
17.11.2014 / 11:58
2

Try this:

<script language="javascript" type="text/javascript">
        function somaPesos(){
            var soma = 0;

            var itens = document.getElementsByClassName("soma");
            for(i = 0; i < itens.length; i++){
                if(!isNaN(itens[i].value)){
                   var item = parseInt(itens[i].value);
                   alert(item);
                   soma = soma + item;
                }                 
            }
            alert(soma);

            return false;
        }
</script>
    
17.11.2014 / 11:56
1

This error NaN (Not a Number) happens when you attempt to do an operation ( + can be a concatenation) with a variable that is not a number.

You probably did not enter a number in the input and then it tries to add a number with something.

    
17.11.2014 / 11:48
0

No html:

<input id="ipTexto" type="text"></input>

No Js:

var inputText = document.getElementById('ipTexto');

At this point, inputText has the entire element. If you need the value, use:

console.log(inputText.value);
    
17.11.2014 / 11:43