The if only recognizes me the last element of the array, what do I do?

1
function comenzar(){
    var caja=document.getElementById("caja");
    var numero=document.getElementById("numero");

    numero.addEventListener("change",background,false);

    setInterval(background(),50);
}
function background(){
     valores=[1,3,5];
        for (i=0; i<valores.length;i++){

        if (numero.value == valores[i]){
            caja.style.background="red";
        }
        else{caja.style.background="#000";}
        }
}
window.addEventListener("load",comenzar,false);
    
asked by Zerlink 10.04.2017 в 17:49
source

1 answer

1

Regardless of the other errors that comment, the main error by which you think that only the last if is executed is because you are comparing different values "numero.value" is string, valors[i] is Integer and also you do not leave the for with break; once the conditions are true to achieve the effect you want.

Make the following correction and it will work for you:

function comenzar(){
    var caja=document.getElementById("caja");
    var numero=document.getElementById("numero");

    numero.addEventListener("change",background,false);

    setInterval(background(),50);
}
function background(){
     valores=[1,3,5];
        for (i=0; i<valores.length;i++){
        if (parseInt(numero.value) == valores[i]){
            caja.style.background="red";
            break;
        }
        else{caja.style.background="#000";}
        }
}
window.addEventListener("load",comenzar,false);
<input id="caja">
<input id="numero">
    
answered by 10.04.2017 в 19:08