Allan Julian Oloo Allan Julian Oloo - 26 days ago 10
Javascript Question

Displaying questions for a quiz using javascript

I am currently doing the javascriptissexy.com learning path. I am having trouble figuring out the best way to display quiz questions. my question is as a beginner javascript student. How should I tackle the approach of developing the behavior of the quiz app. if you look at my code i have stored my questions in a JSON. So how can I display the questions to a user so he or she can answer the question and interact with the program?

var questions = [{

questions: "What is the name of the biggest part of the human brain?",
choices : ["cerebrum", "Thalamus","Medulla", "Cerebellum"],
correstAnswer: 0
},
{
questions: "The colored part of the human eye that controls how much light passes through the pupil is called the?",
choices: ["Pupil", "Rods", "Iris", "Cornea"],
correctAnswer: 2
},
{
questions: "What is the name of the substance that gives skin and hair its pigment?",
choices: ["Dermis", "Melanin", "Swear Gland", "Epiderms"],
correctAnswer: 1
},
{
questions: "The muscles found in the front of your thighs are known as what?",
choices: ["Adductor", "petella", "tibia", "Quadriceps"],
correctAnswer: 3
},
{
questions: "15. The shape of DNA is known as?",
choices: ["Double helix", "Adenine helix", "tri helix", "thymine"],
correctAnswer: 0
},
{
questions: "A structure composed of two or more tissues is termed?",
choices: ["serous membrane", "complex tissue", "organ system", "organ"],
correctAnswer: 3
},
{
questions: "The heart is ____ to the lungs?",
choices: ["superior", "dorsal", "medial", "lateral"],
correctAnswer: 2
},
{
questions: "Male hormones are produced by which of the following?",
choices: ["prostate", "testes", "vas deferens", "prepuce"],
correctAnswer: 1
},
{
questions: "Which of the following terms describes the body's ability to maintain its normal state?",
choices: ["anabolism", "catabolism", "tolerance", "homoestasis"],
correctAnswer: 3
},
{
questions: "Each of the following is known to help prevent infection EXCEPT?",
choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"],
correctAnswer: 3
} ];
/*
* Question variables
*/
var currentQuestions = 0;
var currentAnswer = 0;
var quizDone = false;


$(document).ready(function(){

/*
* Show current question
*/
displayQuestions();

function randomize(questions) {
var currentIndex = questions.length;
var tempQuestion, randomIndex;

//pick remaining element
while (currentIndex > 1 ) {
randomIndex = math.floor(math.random() * currentIndex);
currentIndex -= 1;
tempQuestion = question[currentIndex];
questions[currentIndex] = questions[randomIndex];
questions[randomIndex] = tempQuestion;

}
return questions;
}


});


My codepen link is https://codepen.io/OA11an/pen/jVWMEy?editors=0010

Answer

Here's the solution. Hope it helps!

var questions = [{
  
  question: "What is the name of the biggest part of the human brain?",
  choices : ["cerebrum", "Thalamus","Medulla", "Cerebellum"],
  correstAnswer: 0
},
{
  question: "The colored part of the human eye that controls how much light passes through the pupil is called the?",
  choices: ["Pupil", "Rods", "Iris", "Cornea"],
  correctAnswer: 2
},
{
  question: "What is the name of the substance that gives skin and hair its pigment?",
  choices: ["Dermis", "Melanin", "Swear Gland", "Epiderms"],
  correctAnswer: 1
},
 { 
  question: "The muscles found in the front of your thighs are known as what?",
  choices: ["Adductor", "petella", "tibia", "Quadriceps"],
   correctAnswer: 3
 },
 {
   question: "15. The shape of DNA is known as?",
   choices: ["Double helix", "Adenine helix", "tri helix", "thymine"],
   correctAnswer: 0
 }, 
 {
   question: "A structure composed of two or more tissues is termed?",
   choices: ["serous membrane", "complex tissue", "organ system", "organ"],
   correctAnswer: 3
 },
 {
   question: "The heart is ____ to the lungs?",
   choices: ["superior", "dorsal", "medial", "lateral"],
   correctAnswer: 2
 }, 
  {
    question: "Male hormones are produced by which of the following?",
    choices: ["prostate", "testes", "vas deferens", "prepuce"],
    correctAnswer: 1
  },
   {
     question: "Which of the following terms describes the body's ability to maintain its normal state?",
     choices: ["anabolism", "catabolism", "tolerance", "homoestasis"],
     correctAnswer: 3
   }, 
    {
      question: "Each of the following is known to help prevent infection EXCEPT?",
      choices: ["hair in nose", "mucous membranes", "osteoblasts", "saliva"],
      correctAnswer: 3
    }  ];

$(document).ready(function(){
  
  var questionCounter = 0; //Tracks question number
  var selections = []; //Array containing user choices
  var quiz = $('#quiz'); //Quiz div object
  
  // Display initial question
  displayNext();
  
  // Click handler for the 'next' button
  $('#next').on('click', function () {
    
    // Suspend click listener during fade animation
    if(quiz.is(':animated')) {        
      return false;
    }
    choose();
    
    // If no user selection, progress is stopped
    if (isNaN(selections[questionCounter])) {
      alert('Please make a selection!');
    } else {
      questionCounter++;
      displayNext();
    }
    return false;
  });
  
  // Click handler for the 'prev' button
  $('#prev').on('click', function (e) {
    e.preventDefault();
    
    if(quiz.is(':animated')) {
      return false;
    }
    choose();
    questionCounter--;
    displayNext();
  });
  
  // Click handler for the 'Start Over' button
  $('#start').on('click', function () {
    if(quiz.is(':animated')) {
      return false;
    }
    questionCounter = 0;
    selections = [];
    displayNext();
    $('#start').hide();
    return false;
  });
  
  // Creates and returns the div that contains the questions and 
  // the answer selections
  function createQuestionElement(index) {
    var qElement = $('<div>', {
      id: 'question'
    });
    
    var header = $('<h3>Question ' + (index + 1) + ':</h3>');
    qElement.append(header);
    
    var question = $('<p>').append(questions[index].question);
    qElement.append(question);
    
    var radioButtons = createRadios(index);
    qElement.append(radioButtons);
    
    return qElement;
  }
  
  // Creates a list of the answer choices as radio inputs
  function createRadios(index) {
    var radioList = $('<ul>');
    var item;
    var input = '';
    for (var i = 0; i < questions[index].choices.length; i++) {
      item = $('<li>');
      input = '<input type="radio" name="answer" value=' + i + ' />';
      input += questions[index].choices[i];
      item.append(input);
      radioList.append(item);
    }
    return radioList;
  }
  
  // Reads the user selection and pushes the value to an array
  function choose() {
    selections[questionCounter] = +$('input[name="answer"]:checked').val();
  }
  
  // Displays next requested element
  function displayNext() {
    quiz.fadeOut(function() {
      $('#question').remove();
      
      if(questionCounter < questions.length){
        var nextQuestion = createQuestionElement(questionCounter);
        quiz.append(nextQuestion).fadeIn();
        if (!(isNaN(selections[questionCounter]))) {
          $('input[value='+selections[questionCounter]+']').prop('checked', true);
        }
        
        // Controls display of 'prev' button
        if(questionCounter === 1){
          $('#prev').show();
        } else if(questionCounter === 0){
          
          $('#prev').hide();
          $('#next').show();
        }
      }else {
        var scoreElem = displayScore();
        quiz.append(scoreElem).fadeIn();
        $('#next').hide();
        $('#prev').hide();
        $('#start').show();
      }
    });
  }
  
  function displayScore() {
    var score = $('<p>',{id: 'question'});
    
    var numCorrect = 0;
    for (var i = 0; i < selections.length; i++) {
      if (selections[i] === questions[i].correctAnswer) {
        numCorrect++;
      }
    }
    
    score.append('You got ' + numCorrect + ' questions out of ' +
                 questions.length + ' right!');
    return score;
  }
  
});
body {
  background-image: url(http://7te.org/images/570x363/anatomyhuman-anatomy-human-1280x800-wallpaper-body-wallpaper-76530.jpg);
}
a{
  text-decoration: none;
}

h1 {
  text-align: center;
  font-size: 45px;
  font-family: cursive;
  color: teal;
 text-shadow: 2px 1px black;

  
}
ul {
 margin-right: auto;
 margin-left: auto;
}

li {
 list-style: none;
}

.radiochoices{
  font-family: comic sans ms;
  color: white;
  font-size: 20px;
} 

#container {
    margin:auto;
    width: 50%;
    padding: 0px 0px 30px 0px;
    background-color: #1E90FF;
    border:4px solid #B0E0E6;
    border-radius: 13px;
    color: #FFFFFF;
    font-weight: bold;
    box-shadow: 5px 5px 10px #888;
}

.center {
  margin: 205px 40px 0px 245px
}
.reset {
  display:none;
}
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id='container'>
      <div id='title'>
        <h1 class="title"> Human Anatomy Questions </h1>
      </div>
        <br/>
        <div id='quiz'></div>
        <button class="btn btn-info btn-large" id='next'><a href='#'>Next</a></button>
        <button class="btn btn-warning btn-large reset" id='prev'><a href='#'>Prev</a></button>
        <button class="btn btn-info btn-large" id='start'> <a href='#'>Start Over</a></button>
      </div>