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...
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 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 }
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.