I am creating a small Quiz application where users can create their own quizzes, but have encountered the problem of creating objects in a for loop.
Here is the constructor for the Question object:
var question = function(questionNumber, question, choices, correctAnswer) {
this.questionNumber = questionNumber;
this.question = question;
this.choices = choices;
this.correctAnswer = correctAnswer;
this.populateQuestions = function populateQuestions() {
var h2 = $('<h2>').append(this.question);
$('#quizSpace').append(h2);
for (var i = 0; i < choices.length; i++) {
var radio = $('<input type="radio">').attr({value: choices[i], name: 'answer'});
$('#quizSpace').append(radio);
radio.after('<br>');
radio.after(choices[i]);
}
};
allQuestions.push(this);
};
I have a bunch of HTML that is dynamically generated, and then I pull the values โโand put them in a new object like this:
$('#buildQuiz').click(function() {
var questionLength = $('.question').length;
for ( var i = 1; i <= questionLength; i++ ) {
var questionTitle = $('#question' + i + ' .questionTitle').val();
var correctAnswer = $('#question' + i + ' .correctAnswer').val() - 1;
var inputChoices = [];
$('#question' + i + ' .choice').each(function(){
inputChoices.push($(this).val());
});
var question = new question(i, questionTitle, inputChoices, correctAnswer);
}
allQuestions[0].populateQuestions();
$('#questionBuilder').hide();
$('#quizWrapper').show();
});
However, when I click the #buildQuiz button, I get an error message:
Uncaught TypeError: undefined is not a function
In this line:
var question = new question(i, questionTitle, inputChoices, correctAnswer);
source
share