Home > Enterprise >  Weird behavior with 1 Button
Weird behavior with 1 Button

Time:09-16

I made a simple 1 Button-Game:

var money = 0;

function addOne() {
    money  ;
    document.getElementById("money").innerHTML = money;
}

window.setInterval(function(){
 if(document.getElementById("money").innerHTML >= "50"){
    document.getElementById("timesTwoButtonShop").disabled = false;
  } else {
    document.getElementById("timesTwoButtonShop").disabled = true;
  } 
}, 1);
* {
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">

<p>Money: <b id="money">0</b><b>$</b></p>

<button onclick="addOne();"> 1$</button>

<br><br>

<h1>Shop</h1>
<button id="timesTwoButtonShop">2x for 50$</button>

I made it so that if the money is over or fifty then the 2x for 50$ button will be enabled. But when the money is between $6-$9 the button is somehow enabled. I really don't know how to fix this.

Thanks in advance and have a nice day

CodePudding user response:

Add a parseInt so it isn't string comparison OR use money which is already an int

var money = 0;

function addOne() {
    money  ;
    document.getElementById("money").innerHTML = money;
}

window.setInterval(function(){
 // if (money>=50) {
 if(parseInt(document.getElementById("money").innerHTML) >= 50){
    document.getElementById("timesTwoButtonShop").disabled = false;
  } else {
    document.getElementById("timesTwoButtonShop").disabled = true;
  } 
}, 1);
* {
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">

<p>Money: <b id="money">0</b><b>$</b></p>

<button onclick="addOne();"> 1$</button>

<br><br>

<h1>Shop</h1>
<button id="timesTwoButtonShop">2x for 50$</button>

  • Related