My code is not comparing variables correctly

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) part and in the elseif, it clicks the wrong button instead of clicking the right one.

What could be the error?

Thank you.

    
asked by anonymous 24.07.2017 / 17:24

1 answer

4

You are comparing strings , use parseInt(variavel) to convert it to int , and then compare integer variables, for 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){...
    
25.07.2017 / 22:07