user2197789
user2197789

Reputation: 103

For Loop not working

I want this function to add the two values inputted from the form but instead of adding the values it merges the number. If I input 2 and 2 it comes 22, whereas I want 4 to be outputted. I take it that the for loop is not wotking

<script>
var calculate = function(){
var input = document.getElementsByTagName("input");
var length = input.length;
for (var i = 0; i < length; i++) {
  input[i] = input[i].value;
  input[i] = parseInt(input[i]);
}
var total_living_room = input[0] + input[1];
document.getElementById("sh").innerHTML=total_living_room;
}
</script>

Upvotes: 0

Views: 131

Answers (3)

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Why are you trying to overwrite the input dom element in the array with the value it carries? Change to:

var cache = [];
for (var i = 0; i < length; i++) {
    cache.push(parseInt(input[i].value, 10));
}

Upvotes: 1

Pandian
Pandian

Reputation: 9136

In Your code input[0] and input[1] is Still a Element and you must add its value like below

parseInt(input[0].value) + parseInt(input[1].value)

Fiddle : http://jsfiddle.net/RYh7U/145/

Upvotes: 0

Sirko
Sirko

Reputation: 74106

The problem is, that getElementsByTagName() returns a NodeList and no array (see,e.g., MDN on this).

Both behave similar in many ways, but the elements of a NodeList can not be changed in the way you do.

As a solution parse your values in a second array and use that:

<script>
var calculate = function(){
  var input = document.getElementsByTagName("input"),
      length = input.length,
      inputVals = [];
  for (var i = 0; i < length; i++) {
    inputVals.push( parseInt( input[i].value, 10 ) );
  }
  var total_living_room = inputVals[0] + inputVals[1];
  document.getElementById("sh").innerHTML=total_living_room;
}
</script>

EDIT

Example Fiddle

Upvotes: 5

Related Questions