简体   繁体   中英

JQuery val returning undefined

So I'm calling the following function:

function updateOutput(a){

    var n = $('#selector').val();

    $('#hueslide').val(a[n].hue);
    $('#huetext').val(a[n].hue);
}

And I'm getting an error: "Cannot read property 'hue' of undefined."

However, when I use console.log(n), it's returning a value. And when I manually insert the same value in a[n], I get the expected result. I'm guessing this is an asynchronous issue, but the same code was working in an earlier version and I'm not sure how to fix it.

Specifically, when trying to debug updateOutput using console.log, I get the following:

console.log(n); //returns 0
console.log(a); //returns an array of objects
console.log(a[0]); //returns first object in array
console.log(a(n)); // returns undefined

That error isn't saying that n is undefined, or even a , it's saying that there is no property hue on whatever is assigned to a[n] . Whatever you are passing into updateOutput has no key to match n that also has the property hue .

Try like this:

function updateOutput(a){

   $(document).ready(function(e) {

        var n = $('#selector').val();

       $('#hueslide').val(a[n].hue);
       $('#huetext').val(a[n].hue);


    });  
}

You have to wait until the element are fully loaded. That's why you have to use ready method.

Okay, I figured it out. Turns out the value of 0 in n I was passing a string . So adding n = parseInt(n); resolved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM