Question

I try to set up a quiz with several questions. Each question will use the same input fields like this:

Who was President in 1984?
1 - Carter
2 - Clinton
3 - Reagan
4 - Call a friend!

It must be something that I do not understand. Here is what happens:

I declare an array and a variable:

// Questions Data Structure
var qData = {};
var questionList = new Array();
var curQuestion = parseInt(0);

In a given form the user can enter values within various input fields and textareas. Then user can click a "Save Answers" button before going to the next question in the same web page without postback. The save button do this (gel() is a short for document.getElementById):

curQuestion++;
qData.qQuestionText = gel("questionText").value;

qData.qAnswer1 = gel("Answer1").value;
qData.qAnswer2 = gel("Answer2").value;
qData.qAnswer3 = gel("Answer3").value;
qData.qAnswer4 = gel("Answer4").value;

qData.qAnswerText = gel("AnswerText").value;
questionList[curQuestion] = qData;

The first question is saved OK. Now, believe it or not, when the qData structure change at question 2 (or 3...), the value of ALL elements in the questionList array will change and they will ALL receive the same value!

It is as if all questionList items are permanently linked to qData array! What is wrong?

Was it helpful?

Solution

Your array contains a reference to the object, this is why everything in the array appears to change after each question. It seems you're expecting the object to be cloned when it is pushed to the array, but that is not the case.

Create a new object for each question like so:

curQuestion++;
qData = {}; //  <-------------- create a new object
qData.qQuestionText = gel("questionText").value;

qData.qAnswer1 = gel("Answer1").value;
qData.qAnswer2 = gel("Answer2").value;
qData.qAnswer3 = gel("Answer3").value;
qData.qAnswer4 = gel("Answer4").value;

qData.qAnswerText = gel("AnswerText").value;
questionList[curQuestion] = qData;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top