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>
5
  • 3
    Please define "not working"? What errors do you get? Post your HTML as well. We need a minimal reproducible example Commented Mar 27, 2017 at 21:12
  • That's a terrible duplicate there (it was stackoverflow.com/q/5117127/251311). Sorry community, but removing it, since it is entirely not relevant Commented Mar 27, 2017 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. Commented Mar 27, 2017 at 21:23
  • Yep, and they do it because they don't know how to do it properly. Commented Mar 27, 2017 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"? Commented Mar 27, 2017 at 21:26

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

work like a charm. i try to use object in order to check if the user answer correct. thank you.
@trincot if you can have a look on this stackoverflow.com/questions/43086730/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.