1

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()">
</form>

var firstAmount = 0;    
function depositedFunds(){

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

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

thanks

1
  • 3
    firstAmount += ad.value; Commented Sep 17, 2015 at 11:55

1 Answer 1

4

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) {
  e.preventDefault();
  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">
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

very helpful thanks. just wondering how would you keep the variable in session? your method works but if i close the browser/log out etc it will reset it to 0...
I wouldn't keep it in a session. If I needed to preserve it between sessions then I'd store it in a database on the server and associate it with a session on demand using auth/authz.

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.