SidTheKid SidTheKid - 2 months ago 4
Javascript Question

Can't display number correctly

I'm working on a money management program. There's an input box that you have to type your earnings into. Whenever I input my number and click enter, the number appears on the side but when I add another number it doesn't add up correctly.

HTML

<!DOCTYPE html>
<html>
<head>
<!-- Edit title -->
<title>Banking App</title>
<!-- Stylesheet -->
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<body>
<div class="main">

<header>
<h1>Bank Account Manager</h1>
</header>

<div class="displayInfo">
<div class="displayBalance">
<h2 class="displayBalanceTag">Balance: <span class="displayBalanceNumber"></span></h2>
</div>
</div>
<div class="inputInfo">
<center>
<input type="text" name="earned" placeholder="How Much Have You Earned?" class="earned">
<input type="text" name="spent" placeholder="How Much Have You Spent?" class="spent">
</center>
</div>

</div>

<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main.js -->
<script type="text/javascript" src="assets/js/main.js"></script>
</body>
</html>


JS

// VARIABLES
var balance; //stores users balance
var earnings; //stores users earnings

var earned = $(".earned"); //input users earnings
var spent = $(".spent"); //input users spendings
var displayBalanceNumber = $(".displayBalanceNumber"); //displays users balance

// START
$("document").ready(function () {
balance = 0;

init();
})

// INIT
function init() {
reset(); //resets everything
$(earned).bind("keypress", addEarnings);
}

function addEarnings(e) {
//check for keycode 13 ( enter key )
if(e.which === 13) {
earnings = $(this).val(); //get value from input
balance = balance + earnings;
displayBalanceNumber.html(balance);
displayBalanceNumber.html(balance);
}
}

// RESET
function reset() {
displayBalanceNumber.html(balance); //make value inside balance holder to 0
}

Answer

Your line, balance = balance + earnings;, sees earnings as a string. When you add a string to a number, it converts all of it to a string. What you need to do is convert earnings to an integer. Replace that line with balance = balance + +earnings;. The + converts earnings to an number.