mrdeived
mrdeived

Reputation: 85

Javascript: TypeError variable is undefined

I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:

function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
    for(i=0; i<checkedAnswers.length; i++){
        alert(checkedAnswers[i]);
    }
}

Function checkExerciseRB is my generic function, it is called from checkAnswers.

function checkExerciseRB(rbuttons, opciones, correct){
    var answers = new Array();
    var control = 0;
    for(i=0; i<rbuttons.length; i++){
        var noPick="true";
        for(j=0; j<opciones; j++){
            if(rbuttons[control+j].checked){
                if(rbuttons[control+j].value==correct[i]){
                    answers[i]= 1;
                    noPick="false";
                    break;
                }
                else{
                    answers[i]=2;
                    noPick="false";
                    break;
                }
            }
        }
        if(noPick=="true")
            answers[i]=0;
        control=control+opciones;
    }
    return answers;
}

It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:

TypeError: rbuttons[control + j] is undefined

Any clue on how to deal with this matter?

Upvotes: 5

Views: 27461

Answers (3)

MStodd
MStodd

Reputation: 4746

You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.

Upvotes: 1

Jason Orendorff
Jason Orendorff

Reputation: 45086

This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].

You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.

You’ll watch it, and you’ll think “Oh! That line of code is wrong!”

Upvotes: 7

Jason L.
Jason L.

Reputation: 2484

Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?

Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)

Upvotes: 0

Related Questions