0

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>
trincot
  • 317,000
  • 35
  • 244
  • 286
A. Meshu
  • 4,053
  • 2
  • 20
  • 34
  • 3
    Please define "not working"? What errors do you get? Post your HTML as well. We need a [mcve] – j08691 Mar 27 '17 at 21:12
  • That's a terrible duplicate there (it was http://stackoverflow.com/q/5117127/251311). Sorry community, but removing it, since it is entirely not relevant – zerkms Mar 27 '17 at 21:16
  • @epascarello unless it's not what OP wants. OP does not need variable variables, but a help in choosing one value between the two. – zerkms Mar 27 '17 at 21:23
  • Yep, and they do it because they don't know how to do it properly. – zerkms Mar 27 '17 at 21:24
  • @epascarello top 5 answers there are irrelevant. I'm not sure a good duplicate would be something that requires you to check the least popular answer. Seriously, do you really think spreading `document.write(eval(name));` is a good way to "choose one random value of two"? – zerkms Mar 27 '17 at 21:26

1 Answers1

2

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>
trincot
  • 317,000
  • 35
  • 244
  • 286
  • work like a charm. i try to use object in order to check if the user answer correct. thank you. – A. Meshu Mar 27 '17 at 21:20
  • @trincot if you can have a look on this http://stackoverflow.com/questions/43086730/create-random-arrays-in-javascript – A. Meshu Mar 29 '17 at 07:37