Shinji
Shinji

Reputation: 101

how to add up numbers each time we click on a button

i want to make a program with one input where u put numbers into it. and each time you click, the sum will be added up by the numbers. this is how far i've come and i'm basically stuck here. so please help

buttonAdd.onclick = function () {
  var inputTall = document.getElementById("inputTall").value;
  var a = parseFloat(inputTall);
  var b = 0;
  var c = a + b;
  document.getElementById("pOutput").innerHTML = c;
  d = c + a;
  document.getElementById("pOutput").innerHTML = d;
}
<!DOCTYPE html>
<html lang = "en-US">
  <head>
    <link rel="stylesheet" href="CSS/mystyles.css">
    <meta charset = "UTF-8">
    <title>oppgave 24</title>
    <body>
      <h1>Summer tall</h1>
      <input id="inputTall">
      <button id="buttonAdd";>Legg til</button>
      <hr>
      <br>
      Nylig: <p id="nylig"></p>
      <hr> 
      Sum: <p id= "pOutput"></p>
      <script src="JS/code.js"></script>
    </body>
</html>

as you can see the d= c+a doesn't work and it keeps doubling up the last total.

Upvotes: 0

Views: 1050

Answers (1)

Nick
Nick

Reputation: 292

How about storing the total in a global variable:

var total = 0;
buttonAdd.onclick = function () {
    var inputTall = document.getElementById("inputTall").value;
    var a = parseFloat(inputTall);
    total += a;
    document.getElementById("pOutput").innerHTML = total;
}

Upvotes: 1

Related Questions