0

I have a question and answer section of my site, where the user is asked 6 questions of out 40 possible questions. There are set answers for each one, but there isn't a correct answer. How do I randomize this in Javascript so that the same questions aren't always asked? I know it can be done with an array for the question and answers but don't know how to randomize them then for each page. This is my html code:

    <h2>What is the weather like today?</h2>

    <div class="answers">

    <div class="answers-left">
        <div class="answer1" tabIndex="1">Sunny</div>
        <div class="answer2" tabIndex="2">Raining</div>
    </div>
    <div class="answers-right">
        <div class="answer3" tabIndex="3">Cloudy</div>
        <div class="answer4" tabIndex="4">Windy</div>
    </div>

        <div class="clear"></div>
        </div>

<div class="next-button">
    <a class="ui-btn" href="question-2.html" rel="external">Next</a>
        </div>

As you can see, the user will select an answer and then click next to go to the next question. I only want one question to show at a time. Any help will be greatly appreciated!

1
  • Would you share with us your javascript code and more questions, please? Commented May 8, 2017 at 12:23

1 Answer 1

1

Step 1) Declare a questions table:

var questions = [1, 2, 3, 4, 5, ..., 40];

Step 2) Get the 1st random question

var random1 = Math.floor(Math.random() * questions.length) ;
var choice1 = questions[random1];

Step 3) Remove it from the table

questions.splice(random1, 1);

Repeat steps 2 & 3 to get more questions

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

4 Comments

how would I add answers into this?
@andrea, better create a new question, I'm not sure what you're asking for.
apologies, the question I asked included both the questions and its answers to be randomized, your solution just gave how to randomize the questions only.
@andrea, same principle. Check this out: codepen.io/8odoros/pen/OmQvrE

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.