Freesnöw
Freesnöw

Reputation: 32143

Javascript not running

I have this code here:

var Questions=[]
Questions[0]=["What is the answer?",["A","B","C","D"],3]
Questions[1]=["What is the answer?",["A","B","C","D"],3]
Questions[2]=["What is the answer?",["A","B","C","D"],3]
Questions[3]=["What is the answer?",["A","B","C","D"],3]

function createQuestions(id) {
    var tReturn="<form>"
    tReturn=tReturn+"<b>Questions "+id+":</b>"

    tReturn=tReturn+"</form>"
    return tReturn;
}

for (i=0;i<4;i++) {
    var elem=document.getElementById('quiz_section')
    var func=createQuestion(i)
    elem.innerHTML=elem.innerHTML+func+"<br />"
}

I just started using Javascript recently. I know there must be a syntax error in here somewhere but I can't find it. There is, in fact a DIV in the main document with an id of "quiz_selection".

I don't have access to any kind of debugger because I'm at school and almost everything is blocked.

Thanks if you can!

Upvotes: -1

Views: 115

Answers (4)

kqnr
kqnr

Reputation: 3596

Your function is named createQuestions but you are calling it as createQuestion. Otherwise the syntax seems fine.

Additionally, if this code is embedded immediately into your page it may not function because the document will not fully exist when your for loop executes; hence the quiz_section div will not exist.

Enclose your loop in a function like so:

function initializeQuiz() {
    for (i=0;i<4;i++) {
        var elem=document.getElementById('quiz_section')
        var func=createQuestions(i)
        elem.innerHTML=elem.innerHTML+func+"<br />"
    }
}

And add an onload='javascript:initializeQuiz()' attribute to your <BODY> tag.

Upvotes: 4

Mike Lewis
Mike Lewis

Reputation: 64137

You define createQuestions(), however you are calling createQuestion(), this will naturally throw a ReferenceError.

Also please use semi-colons after each line. ( For good practice )

Upvotes: 3

Matthew Abbott
Matthew Abbott

Reputation: 61589

You could adjust your declaration of your questions to:

var Questions = [
  { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 },
  { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 },
  { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 },
  { Question: "What is the answer?", Values: ["A", "B", "C", "D"], Answer: 3 }
];

That way you can access each item as an object:

var question = Questions[0];
// question.Question
// question.Values
// question.Answer

Upvotes: 1

James Kyburz
James Kyburz

Reputation: 14453

createQuestion should be createQuestions

Upvotes: 2

Related Questions