how to keep adding to JS variable?

I am trying to continuously add to a js variable every time a user enters a value into a box.

So far if they enter '21' the alert will say 'your balance is £12' but then if I enter '15' I want it to say your balance is '27' but instead it says '15' or rather just the latest amount.

The code below:

<form action="" method="get">
  <input type="number" value="" id="amountDropped">
  <input type="submit" value="Deposit amount" onclick="depositedFunds()">

var firstAmount = 0;    
function depositedFunds(){

    var ad = document.getElementById("amountDropped");

    firstAmount = +firstAmount + +ad.value;
    alert ("Your balance is £" + firstAmount);




The function which makes the change is attached to a submit button.

When the user clicks the button:

  1. The JS runs
  2. The value is updated
  3. The value is alerted
  4. The form is submitted
  5. A new page loads
  6. The new page has var firstAmount = 0; in it

You should:

  • Set the default value dynamically with server side code. See Unobtrusive JavaScript and
  • Prevent the default behaviour of the submit button

Using an onclick attribute, you need to return false from the event handler function:

onclick="depositedFunds(); return false;"

Modern code would separate concerns and not tie things so tightly to a specific means of triggering the form submission.

var firstAmount = 0;

function depositedFunds(e) {
  var ad = document.getElementById("amountDropped");
  firstAmount = +firstAmount + +ad.value;
  alert("Your balance is £" + firstAmount);

document.querySelector('form').addEventListener('submit', depositedFunds);
<form method="get">
  <input type="number" id="amountDropped">
  <input type="submit" value="Deposit amount">


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.