Reputation: 101
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
Upvotes: 1
Views: 2127
Reputation: 943142
The function which makes the change is attached to a submit button.
When the user clicks the button:
var firstAmount = 0;
in itYou should:
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>
Upvotes: 4