SidTheKid SidTheKid - 5 months ago 16
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.


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

<h1>Bank Account Manager</h1>

<div class="displayInfo">
<div class="displayBalance">
<h2 class="displayBalanceTag">Balance: <span class="displayBalanceNumber"></span></h2>
<div class="inputInfo">
<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">


<!-- JQuery -->
<script src=""></script>
<!-- Main.js -->
<script type="text/javascript" src="assets/js/main.js"></script>


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

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


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;

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


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.