简体   繁体   中英

Javascript: Add or Subtract to running total

I am very new to Javascript, only a few weeks, and am stuck on something I assume to be simple. I have searched for hours, but cant find an example to point me in the right direction. Im basically wanting to create a simple "Running Balance" calculator. One textbox has the input (added by using add button) and the other textbox has the output. The output should change depending on what I put into the input textbox and keep adding to the value in the output textbox.

Here is my code in Javascript:

var accountBalance = 0;

function addBalance()
{
    var inPrice = document.getElementById("inAmt").value 
    total = parseInt(inPrice += accountBalance);        
    document.getElementById("outBalance").value = total;
}

and the HTML:

<form id="form2" name="form2" method="post" action="">
<p>
Enter an amount: 
<input type="text" name="inAmt" id="inAmt" />
</p>
<p>
Display Balance:: 
<input type="text" name="outBalance" id="outBalance" />
</p>
</form>

<p><input type="button" id="addBal" value="Add the amount to the balance" onclick="addBalance()"/></p>

I have a feeling my total variable in my function is what I am screwing up. Thanks in advance for the help!!

This part doesn't really make sense:

total = parseInt(inPrice += accountBalance);

It takes accountBalance ( 0 ), appends it to inPrice (since inPrice is a string), stores the value back in inPrice , parses the result as an integer, and sets total to that integer. What you seem to need is pretty much the reverse, that is:

  • Parse inPrice so that it's a number instead of a string
  • Add it to accountBalance and store the result in accountBalance
  • Put the new accountBalance in total (or just use accountBalance in the first place)

Or, in JavaScript:

var accountBalance = 0;

function addBalance() {
    var inPrice = document.getElementById("inAmt").value
    
    document.getElementById("outBalance").value = ;
}

You've confused a few variables - the problem was you were never reading the current balance and you were resetting the total variable every time (aside from mixing ints and strings). Here is a version without the total variable:

function addBalance()
{
    var inPrice = document.getElementById("inAmt").value 
    accountBalance += parseInt(inPrice, 10);        
    document.getElementById("outBalance").value = accountBalance;
}

See it here: http://jsfiddle.net/fdureo1s/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM