doriansm
doriansm

Reputation: 245

Variable not changing in IF statement

I am a JS beginner, so I am having some trouble with this one.

I have a variable called morale, and it updates based on some math. This is working just fine. What I am now trying to do is basically log the highest number morale has ever been, that way I can do some maths based off max morale. The max_morale is not changing at all, even though the morale is. I figured this code should work fine, but it is not. I do have <span id="max_morale">0</span> in my HTML. Please help!

var morale = 0;
var max_morale = 0;
var money = 0;

function increment(number){
    money = money + number;
    document.getElementById("money").innerHTML = addCommas(money);
};


function moraleCalc(){
    morale = Math.floor(money * 0.0009)+"%";
    document.getElementById('morale').innerHTML = morale;
        if(morale > max_morale){
        max_morale = morale;
        document.getElementById('max_morale').innerHTML = max_morale;
    };    
};

window.setInterval(function(){
    moraleCalc();
}, 1000);

Upvotes: 0

Views: 82

Answers (2)

wintvelt
wintvelt

Reputation: 14101

I think your problem arises when you calculate morale. By adding the +"% to the calculation, you change morale from a number type to a string. After that your comparison becomes unpredictable.

Better leave morale a number, and change to string when assigning to innerHTML

morale = Math.floor(money * 0.0009);
....
document.getElementById('max_morale') = 

max_morale.toString() + '%';

Upvotes: 0

Reinard
Reinard

Reputation: 3654

morale is a string value because you append "%", not a number.

You are comparing the string to an Integer.

Upvotes: 5

Related Questions