[Solved] Javascript / Html Check box error [closed]


On line 68 of your code, you set y to be the number of questions the user asked for.

y=document.getElementById("myForm").elements[0].value;

This loop (starting on line 102) is where the error is coming from:

for(var i=0; i<y; i++){
    if(choices[i].checked){
        choice = choices[i].value;
    }
}

Here’s what happens: If you ask for 4 questions, this loop will keep running as long as i is less than 4. When i is 3, the if statement will be trying to access choices[3].checked. Remember, choices[3] is actually the 4th item in the array since indexes start at 0. Each question only has 3 choices, so when you ask for the 4th one you get undefined.

But you want this loop to look at 3 and only 3 answers for each question, regardless of how many questions there are in total. What you probably meant to write was this:

for(var i=0; i<3; i++){
    if(choices[i].checked){
        choice = choices[i].value;
    }
}

0

solved Javascript / Html Check box error [closed]