730
730

Reputation: 21

Function with if-else doesn't work properly

I made a function which should disable a button if a variable isn't greater than or equal to another one. This function is run every second on a setInterval(), and the first variable to compare is also incremented by one on the setInterval(). But, the function (evitarNegs()), isn't working properly, and the button is always disabled. Sorry that part of the code is in spanish.

Javascript:

var GmB = {cantidad: 0, perSec: 1};

function Upgrade (pb, ps) {
    this.precioBase = pb;
    this.perSec = ps;
    this.cantidad = 0;
    this.precio = pb;
}

Upgrade.prototype.comprar = function() {
    GmB.cantidad = GmB.cantidad - this.precio;
    GmB.perSec = GmB.perSec + this.perSec;
    this.cantidad++;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    this.precio = Math.ceil(this.precioBase*Math.pow(1.15, this.cantidad));
    evitarNegs();
};

function loop() {
    GmB.cantidad = GmB.cantidad + GmB.perSec;
    document.getElementById("gmb").innerHTML = GmB.cantidad;
    evitarNegs();
}

var upg = new Upgrade(10, 1);
var boton1 = document.getElementById("boton1");
boton1.disabled = true;
window.setInterval(loop, 1000);

//Problematic function
function evitarNegs() {
    if (!(GmB >= upg.precio)) {
        boton1.disabled = true;
    }else {
        boton1.disabled = false;
    }
}

boton1.onclick = function() {
    upg.comprar();
};

HTML:

<html>
    <head>
        <title>Gummy Bears</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">

    </head>
    <body>
        <p id="gmb">0</p>
        <button id="boton1" type="button">Upgrade 1</button>
        <script src="main.js"></script>
    </body>
</html>

Upvotes: 0

Views: 60

Answers (2)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

You are comparing GmB to upg.precio, but GmB is an object. So you want

function evitarNegs() {
    if (!(GmB.cantidad >= upg.precio)) {
        boton1.disabled = true;
    } else {
        boton1.disabled = false;
    }
}

However, this can be written much easier as

function evitarNegs() {
    boton1.disabled = GmB.cantidad < upg.precio;
}

Fiddle: http://jsfiddle.net/4rRmp/

Upvotes: 3

R&#233;mi
R&#233;mi

Reputation: 689

It seems that you are comparing an object to an integer in GmB >= upg.precio. You probably have to replace it by GmB.cantidad >= upg.precio.

Upvotes: 1

Related Questions