Reputation: 4148
I'm trying to write script that will show random question. I can't figure out how to do that.
This is my NOT WORKING ( = doesn't write anything on the element) code:
function theQ(quest, ans) { // question constructor
this.question = quest;
this.answer = ans;
}
var quest1 = new theQ("1+1", "2"); // object 1
var quest2 = new theQ("2+2", "4"); // object 2
var container = document.getElementById("rendomQuestion"); // display
var randomNumber = Math.random(); // randomize
var numQuestion = Math.floor(randomNumber * theQ.length); // between theQ number of objects
container.innerHTML += quest+numQuestion.question; // write the chosen question.
Please tell me what am i doing wrong here..
Edit - this is my HTML:
<p id="rendomQuestion"></p>
Upvotes: 0
Views: 111
Reputation: 350310
You should use an array (of two questions):
function theQ(quest, ans) { // question constructor
this.question = quest;
this.answer = ans;
}
// *** Make it an array:
var quests = [new theQ("1+1", "2"),
new theQ("2+2", "4")];
var container = document.getElementById("rendomQuestion");
var randomNumber = Math.random();
var numQuestion = Math.floor(randomNumber * theQ.length);
// *** Now use array notation:
container.textContent = quests[numQuestion].question;
<p id="rendomQuestion"></p>
Upvotes: 2