0

I am trying to capture user input from a form by getting the values and then pushing them into an array. I then want to output them with an alert but for some reason the values are getting concatenated instead of added. I also have a random zero with my output. I should be getting the total of the three values (example 1+2+3 should give 6, not 0123. Please advise thanks!

function myFunction() {
    var totalArray = [];
    
    totalArray.push(document.getElementById('votes1').value);
    totalArray.push(document.getElementById('votes2').value);
    totalArray.push(document.getElementById('votes3').value);
    
    var totalAmount = 0;
    
    for (var x = 0; x < totalArray.length; x++) {
    
        totalAmount += totalArray[x];
    }
    
    alert(totalAmount); 
}

myFunction();
<input id="votes1" value="1"/>
<input id="votes2" value="2"/>
<input id="votes3" value="3"/>

3 Answers 3

2

you can use parseInt to convert values to integers before adding them, like this:

totalAmount += parseInt(totalArray[x]);
Sign up to request clarification or add additional context in comments.

1 Comment

wow duh!! something so easy thank you!! totally overlooked that
2

The value property .value return a string value so you should parse this value to number if you want to perform any calculation :

totalAmount += Number(totalArray[x]);

Else the + will concatenate the values as strings.

Hope this helps.

function myFunction() {
  var totalArray = [];

  totalArray.push(document.getElementById('votes1').value);
  totalArray.push(document.getElementById('votes2').value);
  totalArray.push(document.getElementById('votes3').value);

  var totalAmount = 0;

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

      totalAmount += Number(totalArray[x]);
  }

  alert(totalAmount); 
}

myFunction();
<input id="votes1" value="1"/>
<input id="votes2" value="2"/>
<input id="votes3" value="3"/>

Comments

1

Simplified your code a lil' bit.

const count = () => {
  let totalAmount = 0,
      numberOfInputs = 3;
      
  for (let i = 1; i <= numberOfInputs; i++) {
    totalAmount += Number(document.getElementById(`votes${i}`).value);
  }
  
  console.log(totalAmount); // return
}

document.getElementById('btn').addEventListener('click', count);
<input id='votes1'>
<input id='votes2'>
<input id='votes3'>
<button id='btn'>Count</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.