-1

Can someone help me to get sum of pushed numbers to array ? I need to get sum displayed after 20th Rounds. I push scorePoint which is typed by player and all the score need to be multiplied after 20 round to see result.

var round = 1;
var score1 = [];

function roundNr() {
  round++;
  document.getElementById("p").innerHTML = round;
}

function scoreCntr() {
  var scorePoint1 = document.getElementById('score1').value;
  score1.push(scorePoint1);

  if (round > 20) {
    document.getElementById("score").innerHTML = score1;
  }
}
<div class="input_box">
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>
</div>

<div class="round_box">
  <h1>ROUND</h1>
  <p id="p">1</p>
</div>

<div id="score">

</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • You have an array of strings, not numbers, but otherwise: https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers –  Jun 14 '18 at 14:01
  • `score1.push(+scorePoint1); ...innerHTML = score1.reduce((a, b) => a + b, 0);` – mplungjan Jun 14 '18 at 14:02
  • Thank you so much ! I am student at javascript, so i didnt know about it. But anyways thanks for info. – Edward Leks Jun 14 '18 at 15:55

1 Answers1

1

You are missing score1.forEach(val=>sum+=parseInt(val)); inside the if condition that will calculate the sum. Also note that when you push the value it is string type so you need to use parseInt() to get the integer value before adding them.

var round = 1;
var score1 = [];

function roundNr() {
  round++;
  document.getElementById("p").innerHTML = round;
}

function scoreCntr() {
  var scorePoint1 = document.getElementById('score1').value;
  score1.push(scorePoint1);

  if (round > 20) {
    var sum = 0;
    score1.forEach(val=>sum+=parseInt(val));
    document.getElementById("score").innerHTML = sum;
  }
}
<div class="input_box">
  <input type="name" placeholder="Name" id="name1">
  <input type="text" placeholder="Score" id="score1">
  <button onclick="roundNr(); scoreCntr();">Submit</button>
</div>

<div class="round_box">
  <h1>ROUND</h1>
  <p id="p">1</p>
</div>

<div id="score">

</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62