0

I have a script that contains 3 questions. I have started by creating 3 variables (ex: var q1 = "question here") and I have a function that randomly picks a number between 1 and 3 and chooses that question (var question = "q" + rand;) but if I want to reference this variable called question to output the question in HTML (ex: document.getElement.Id("output").innerHTML += question;) how would I do so?

Here is my code:

// Questions List
        var q1 = " Question 1 here"
        var q2 = "Question 2 here"
        var q3 = "Question 3 here"

  // Randomly generate a question and then output it
        var randy = Math.floor(Math.random()*3+1);
        var question = "q" + randy;
        document.getElementById("output").innerHTML += question;
        
    
<!doctype html>
<html>
<body>
  <div id="output"></div>
</body>
</html>

So basically the script will choose a question from 1 to 20 and output it to my HTML div tag.

Sorry if this isn't clear. Any help is greatly appreciated.

  • Don't use dynamic variables, use an array. – Barmar Dec 09 '21 at 18:58
  • had you have a look to [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/)? – Nina Scholz Dec 09 '21 at 18:58
  • User array or object of questions and access them by using keys. – Bulent Dec 09 '21 at 18:58
  • Why not have the questions written in html and show them or hide them based on the random selection? This seems more straightforward, but either way you need a way to select the question you want by using JSON or other data structures as the way you are defining the variable won't work to select the question you want – ViaTech Dec 09 '21 at 19:00
  • Okay, I used an array it worked. Thanks. – Cool Stuff108 Dec 09 '21 at 19:12

0 Answers0