My code is not properly comparing variables

Asked

Viewed 79 times

3

setInterval(function(){
    $.getJSON("http://127.0.0.1/recebecores/valor.php", function(array) {
        quantidade = array[0];
        document.getElementById('betAmount').value = quantidade;
        var tempo  = document.getElementById("banner").textContent;
        var match  = tempo.match(/[^\d](\d+)/);
        var nr     = match && match[1];
        if(nr    === "4"){
            var red   = document.getElementById("red").textContent;
            var green = document.getElementById("green").textContent;
            var black = document.getElementById("black").textContent;
            console.log(red);
            console.log(black);
            if(red>black){
                $("#enviarpreto").click();
            }else if(black>red){
                $("#enviarvermelho").click();
            }
         }
     });
},1000);

Well, sometimes in the if(red > black) and elseif part, he clicks the wrong button instead of clicking the right one.

What could be the mistake?

Thank you.

  • What are the values of the variables red and black?

  • Are numbers, which may vary....

  • If it’s numbers, we’re missing one parse. You are storing the values in string in the variables.

  • parse, what do you mean? Could you give an example?

  • 4

    Convert the value of stored variables to string in int using parseint or in floatusing parseFloat.

1 answer

4

Are you comparing strings, use parseInt(variavel) to convert it into a int, and then compare the whole variables, follow example:

var red   = parseInt(document.getElementById("red").textContent);
var green = parseInt(document.getElementById("green").textContent);
var black = parseInt(document.getElementById("black").textContent);

//Agora a comparação de "maior que" funcionara corretamente
if(red>black){...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.