Get this error: “Uncaught TypeError: Cannot read property ‘0’ of undefined”

EDIT: Just seen youve posted your html in a comment – your html does not have any form elements, hence document.forms[0] will be undefined.

In general, the error “Uncaught TypeError: Cannot read property '0' of undefined” comes about when you try to access a variable whose value is undefined using an array-like square bracket syntax.

The code below demonstrates this in a rather convoluted way (Setting up a function with a parameter, only to call the function without passing an argument, making that parameter undefined. Watch the console for the error)

function doSomething(myArray){


Now, in your code this really only boils down to 1 thing, either document.forms is undefined or on one of the iterations of your loop document.forms[0].correctX is undefined (where X is a value from your loop).

Without seeing your HTML, it is impossible to ascertain what exactly is happening, but you can debug it by stepping through until the error is occurred and looking at the value of i.

As an aside, and has been mentioned in comments eval is unnecessary here, you can use the square bracket notation to dynamically access objects, and this may also help you debug:

var isYesChecked = document.forms[0]["correct"+i][0].checked;

Browse More Popular Posts

Leave a Comment