Cannot Read Property 'Length' of Undefined

I've been looking at the other posts on this error but can't seem to figure it out in this situation. I'm trying to save to localstorage, but I get this error and it says that the "radio" variable is undefined, but it doesn't seem to be. I'm using JQMobile as well. Here's the fiddle: Line 28 seems to be the problem.

Here's the function:

var getSelectedRadio = function(){
        var radios = document.forms[0].acoustic;
        for(var i=0, j=radios.length; i<j; i++){
            if(radios[i].checked) {
            console.log(acousticValue);
                acousticValue = radios[i].value;

            }
        }
        return acousticValue;

};
3

3 Answers

You can't read properties of undefined. It doesn't have properties, typically (see ).

So, before you try to read its length, make sure it's not undefined. Or that it has a length, like

if (obj.length) { your code }

This presumes that obj is not undefined. If you're not sure about that either, then:

if (obj && obj.length) { your code }
0
document.forms[0].acoustic

Doesn't exist and therefore is undefined. When you set radios to that and then try to find the length, it fails.

You probably need to be looking for a different object, or at least checking to see if the object exists before attempting to iterate over it.

Please check the typeof variable(radios). It seems to be object. This error won't come if it is an array.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest