user7142440
user7142440

Reputation: 3

Javascript: how to get the value of a changing input

I have this code but I can't get the value of the input into helpCallback(), all I get is undefined. I have to do it with a closure.

function tablaR(num){
    var seccion=document.getElementById("tabla");
    seccion.innerHTML="";
    seccion.style.display='block';

    for (var i = 0; i < 11; i++) {
        var prod=parseInt(num*i);
        var t=document.createTextNode(num+" x "+i+"= ");
        var inp=document.createElement('INPUT');

        inp.setAttribute('type', 'number');
        inp.setAttribute('id', 'resul');

        inp.addEventListener("change", helpCallback(num, this.value));
        var para=document.createElement("p");
        para.appendChild(t);
        para.appendChild(inp);
        seccion.appendChild(para);
    }
}

function helpCallback(prod, resp){
    return function(){
        resp=parseInt(inp.value);
        if(resp!=prod){
            this.style.color = "red";
        }
        else{
            this.style.color = "green";
        }
    }
}

Upvotes: 0

Views: 40

Answers (1)

adeneo
adeneo

Reputation: 318182

this is not the element where you're executing the helpCallback function, but you could just get the value inside the returned function instead

inp.addEventListener("change", helpCallback(num));

function helpCallback(prod){
    return function(){
        var resp = parseInt(this.value, 10);

        if(resp!=prod){
            this.style.color = "red";
        } else{
            this.style.color = "green";
        }
    }
}

Upvotes: 1

Related Questions