0

Thank you very much for everyone who has helped me out previously with this assignment. I finally got the pictures to randomize and show up one at a time after clicking "next". However, when I click "next" the same picture keeps showing up and aren't matched up to the answer options. How can I fix this? Thank you very much.

var questionCounter = 0;

var quiz = [
{
  "question": "https://cheesecake.articleassets.meaww.com/395831/uploads/a4ba7dc0-215a-11ea-9d42-2d0f11d5ecba_800_420.jpeg",
  "choices": ["Emperor Palpatine", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Emperor Palpatine"
}, 
{
  "question": "https://img.cinemablend.com/filter:scale/quill/6/c/b/3/7/3/6cb373581fd3066afa89e6afa466b2307b814e59.jpg?mw=600",
  "choices": ["Yoda", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Yoda"
}, 
{
  "question": "https://img.cinemablend.com/filter:scale/quill/7/a/d/0/9/4/7ad0949f28faa4df5e2ddc5e03272c56fa6c2764.jpg?fw=1200",
  "choices": ["Han Solo", "Commander Cody", "R2-D2", "Boba Fett"],
  "correct": "Han Solo"
}, 
{
  "question": "https://lumiere-a.akamaihd.net/v1/images/Darth-Maul_632eb5af.jpeg?region=75%2C42%2C1525%2C858&width=960", 
  "choices": ["Darth Maul", "General Grievous", "Count Dooku", "Darth Vader"],
  "correct": "Darth Maul"
}, 
{
  "question": "https://thedisneyblog.com/wp-content/uploads/2019/10/star-wars-episode-3-obi-wan-kenobi.jpg", 
  "choices": ["Obi-Wan Kenobi", "Princess Leia", "Chewbacca", "Jar Jar Binks"],
  "correct": "Obi-Wan Kenobi"
}, 
{
  "question": "https://lumiere-a.akamaihd.net/v1/images/General-Grievous_c9df9cb5.jpeg?region=0%2C0%2C1200%2C675&width=960",
  "choices": ["General Grievous", "Plo Koon", "Nute Gunray", "Darth Plagueis"],
  "correct": "General Grievous"
}, 
{
  "question": "https://www.roadtovr.com/wp-content/uploads/2019/05/star-wars-vader-immortal-4.jpg",
  "choices": ["Darth Vader", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Darth Vader"
}, 
{
  "question": "https://i2.wp.com/sabersourcing.com/wp-content/uploads/2020/07/darth-plagueis-lightsaber-lightsaber-profile.jpg?fit=1368%2C752&ssl=1",
  "choices": ["Darth Plagueis", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Darth Plagueis"
}, 
{
  "question": "https://static1.srcdn.com/wordpress/wp-content/uploads/2019/05/count-dooku.jpg",
  "choices": ["Count Dooku", "General Grievous", "Darth Maul", "Han Solo"],
  "correct": "Count Dooku"
}, 
{
  "question": "https://starwarsblog.starwars.com/wp-content/uploads/2017/01/c3po-revenge-of-the-sith-1536x864-473996094288.jpg",
  "choices": ["C-3PO", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "C-3PO"
}, 
{
  "question": "https://cdn.onebauer.media/one/media/5d72/5e04/ddd8/9ce2/65de/cd3a/star-wars-r2-d2-tall-image.jpg?quality=50&width=1800&ratio=16-9&resizeStyle=aspectfill&crop=2,179,763,1532&format=jpg",
  "choices": ["R2-D2", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "R2-D2"
}, 
{
  "question": "https://storage.googleapis.com/spikeybits-staging-bucket/2018/11/cody.jpg",
  "choices": ["Commander Cody", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Commander Cody"
}, 
{
  "question": "https://wegotthiscovered.com/wp-content/uploads/2020/05/158515416174369896-38.jpeg",
  "choices": ["Boba Fett", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Boba Fett"
}, 
{
  "question": "https://images.squarespace-cdn.com/content/v1/51b3dc8ee4b051b96ceb10de/1589735227430-HQR8PHUBVO2R3GZEVV55/ke17ZwdGBToddI8pDm48kNvT88LknE-K9M4pGNO0Iqd7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z5QPOohDIaIeljMHgDF5CVlOqpeNLcJ80NK65_fV7S1USOFn4xF8vTWDNAUBm5ducQhX-V3oVjSmr829Rco4W2Uo49ZdOtO_QXox0_W7i2zEA/image-asset.jpeg?format=2500w",
  "choices": ["Luke Skywalker", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Luke Skywalker"
}, 
{
  "question": "https://static2.cbrimages.com/wordpress/wp-content/uploads/2016/12/princess-leia-endor.jpg?q=50&fit=crop&w=740&h=370",
  "choices": ["Princess Leia", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Princess Leia"
}, 
{
  "question": "https://starwarsblog.starwars.com/wp-content/uploads/2020/04/best-friend-in-galaxy-chewbacca_TALL.jpg",
  "choices": ["Chewbacca", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Chewbacca"
}, 
{
  "question": "https://lumiere-a.akamaihd.net/v1/images/databank_jarjarbinks_01_169_c70767ab.jpeg?region=0%2C0%2C1560%2C780",
  "choices": ["Jar Jar Binks", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Jar Jar Binks"
}, 
{
  "question": "https://lumiere-a.akamaihd.net/v1/images/databank_kitfisto_01_169_21517d01.jpeg?region=0%2C49%2C1560%2C780",
  "choices": ["Kit Fisto", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Kit Fisto"
}, 
{
  "question": "https://i.ytimg.com/vi/FXLaHwcTarg/maxresdefault.jpg",
  "choices": ["Plo Koon", "General Grievous", "Darth Maul", "Count Dooku"],
  "correct": "Plo Koon"
}, 
{
  "question": "https://lumiere-a.akamaihd.net/v1/images/databank_nutegunray_01_169_9d66ded2.jpeg?region=0%2C0%2C1560%2C780", 
  "choices": ["Nute Gunray", "Yoda", "Darth Vader", "Han Solo"],
  "correct": "Nute Gunray"
}
];

var currentQuestion = Math.floor(Math.random() * quiz.length);

quiz.forEach(q => q.choices.sort(() => Math.random() - .5));


var content = $("content"),
  questionContainer = $("question"),
  choicesContainer = $("choices"),
  scoreContainer = $("score"),
  questionNumberContainer = $("questionNumber"),
  submitBtn = $("submit");


  score = 0,
  askingQuestion = true;

function $(id) {   return document.getElementById(id);
}

function askQuestion() {

    questionCounter++;

  var choices = quiz[currentQuestion].choices,
    choicesHtml = "";

  for (var i = 0; i < choices.length; i++) {
    choicesHtml += "<input type='radio' name='quiz" + currentQuestion +
      "' id='choice" + (i + 1) +
      "' value='" + choices[i] + "'>" +
      " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>";
  }

  questionContainer.innerHTML = "<img src=\"" + question + "\" width=\"450\" height=\"236\"><br>";

 questionNumberContainer.textContent = "Question" + " " + (questionCounter) 

  choicesContainer.innerHTML = choicesHtml;

  if (questionCounter === 1) {
    scoreContainer.textContent = "Score: 0 right answers out of " +
      quiz.length + " possible.";
    submitBtn.textContent = "Submit Answer";


  }

}

  question = quiz[currentQuestion].question;
  choices = quiz[currentQuestion].choices; 
  correct = quiz[currentQuestion].correct; 


function checkAnswer() {

  if (askingQuestion) {
    submitBtn.textContent = "Next Question";
    askingQuestion = false;

    var userpick,
      correctIndex,
      radios = document.getElementsByName("quiz" + currentQuestion);
    for (var i = 0; i < radios.length; i++) {
      if (radios[i].checked) { 
        userpick = radios[i].value;
      }

      if (radios[i].value == quiz[currentQuestion].correct) {
        correctIndex = i;
      }
    }

    var labelStyle = document.getElementsByTagName("label")[correctIndex].style;
    labelStyle.fontWeight = "bold";
    if (userpick == quiz[currentQuestion].correct) {
      score++;
      labelStyle.color = "green";
    } else {
      labelStyle.color = "red";
    }
    
    scoreContainer.textContent = "Score: " + score + " right answers out of " +
      quiz.length + " possible.";

  } else {
    askingQuestion = true;
    submitBtn.textContent = "Submit Answer";
    if (currentQuestion < quiz.length + 1) {
      currentQuestion++;
      askQuestion();
    } else {
      showFinalResults();
    }
  }
}

function showFinalResults() {
  content.innerHTML = "<h2>Quiz Completed.</h2>" +
    "<h2>Below are your results:</h2>" +
    "<h2>" + score + " out of " + quiz.length + " questions, " +
    Math.round(score / quiz.length * 100) + "%<h2>";
}

window.addEventListener("load", askQuestion, false);
submitBtn.addEventListener("click", checkAnswer, false);
  • for the randomizing the questions, you can randomize the array, see the brief detail at the link given, that how you can randomize an array by de-facto unbiased shuffle algorithm which is Fisher-Yates (aka Knuth) Shuffle. https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Mujtaba Oct 31 '20 at 19:53
  • Hello. Thanks for your response. I actually got the questions to randomize but can't figure out to get the answer options (a, b, c, d) to randomize. – ChristianT123 Oct 31 '20 at 19:55
  • 2. and for saving the results, you can use the localstorage and reference it from there. see more at https://developer.mozilla.org/en-US/docs/DOM/Storage 3. and for highlighting you can make use of jQuery Effect - Highlight Effect, see more at: https://www.tutorialspoint.com/jquery/effect-highlight.htm – Mujtaba Oct 31 '20 at 19:58
  • Put the answers into a separate array and shuffle that array. You'll also have to keep track of which answer is the correct one, since "A" is no longer necessarily the first answer (even though it may display like that to the user). – kmoser Oct 31 '20 at 19:59
  • as @kmoser said, in addition, you can put your answers in another array (multidimensional arrays) and you can than shuffle both. See more about multidimensional arrays at: https://www.javascripttutorial.net/javascript-multidimensional-array/ – Mujtaba Oct 31 '20 at 20:03
  • Thank you! And after adding the answers to a separate array, would I have to change any code here: question = questions[pos].question; chA = questions[pos].a; chB = questions[pos].b; ... – ChristianT123 Oct 31 '20 at 20:06
  • Yes, that would have to change because it would no longer be hardcoded to retrieve the answers from elements `.a`, `.b`, etc. Instead, it would retrieve them from the shuffled array of answers. – kmoser Oct 31 '20 at 20:34
  • Thank you. I added the answers to a separate array but now, the answers aren't linking to the specific picture. For example, if there is a picture of Darth Vader, there are no options in the answers for Darth Vader. – ChristianT123 Oct 31 '20 at 20:43
  • What would I add instead of the chA = answers[pos].a; etc to retrieve the answers? Would the following have to change as well? test.innerHTML += ""; – ChristianT123 Oct 31 '20 at 21:20

1 Answers1

0

You need to do two basic things: create a random order for the answers, and keep track of which answer goes in which position (A-D).

This can be done with a single hash, but for simplicity I'm using two variables: answerLetters is an array of letters (A-D) which gets shuffled to a random order (shuffle code left as an exercise for the reader), and answersKey is a hash in which keys are answer letters (A-D) and values are the corresponding answer text.

function renderQuestion() {
  test = get("test");
  if (pos >= questions.length) {
    test.innerHTML = "<h2>You got " + correct + " of " + questions.length + " questions correct!</h2>";
    get("test_status").innerHTML = "Quiz Completed";

    pos = 0;
    correct = 0;

    return false;
  }
  get("test_status").innerHTML = "Question " + (pos + 1) + " of " + questions.length;

  question = questions[pos].question;

  let answerLetters = [ 'A', 'B', 'C', 'D' ]; // Order is irrelevant since we are about to sort them:
  shuffle( answerLetters ); // Left as an exercise for the reader. See https://stackoverflow.com/a/6274381/378779

  // Key is an answer letter (A-D), values are corresponding answer text:
  let answersKey = {
    'A': questions[pos].a,
    'B': questions[pos].b,
    'C': questions[pos].c,
    'D': questions[pos].d
  };

  img = questions[pos].img;

  test.innerHTML = "<h3>" + question + "</h3>";
  
  test.innerHTML += "<img src=\"" + img + "\" width=\"450\" height=\"236\"><br>";

  // For each answer letter (in shuffled order), append a radio button whose value is that letter and whose text is the corresponding answer text:
  answerLetters.forEach( function( answerLetter ) {
    test.innerHTML += "<label> <input type='radio' name='choices' value='" + answerLetter + "'> " + answersKey[answerLetter] + "</label><be>";
  } );
  
  test.innerHTML += "<button onclick='checkAnswer()'>Next</button>";
}
kmoser
  • 8,780
  • 3
  • 24
  • 40