Cloud Stack Ninja

$("#question2").hide();
const options = [$(".option1"), $(".option2"), $(".option3"), $(".option4")];

let randomOption = function() {
  const texts = options
    .map(opt => opt[0].textContent)
    .sort(() => .5 - Math.random());

  $(".option1").text(texts[0]);
  $(".option2").text(texts[1]);
  $(".option3").text(texts[2]);
  $(".option4").text(texts[3]);
}



$("#question1 button").click(function() {
  if ($(this).hasClass("correct")) {
    $("#question1").fadeOut();
    $("#question2").fadeIn();
  } else {
    $(this).text("X")
  }
})
$("#question2 button").click(function() {
  if ($(this).hasClass("correct")) {
    $("#question2").fadeOut();
    $("#question1").fadeIn();
  } else {
    $(this).text("X")
  }
})

console.log(randomOption())
button {
  background-color: rgb(192, 235, 179)
}

.container {
  margin-top: 300px;
  display: flex;
  justify-content: center;
  align-self: center;
}

button {
  font-size: 50px;
  margin: 30px;
  width: 80px;
}
<div class="container">
  <div id="question1">question 1
    <button class="option1 correct">1</button>
    <button class="option2">2</button>
    <button class="option3">3</button>
    <button class="option4">4</button>
  </div>
  <div id="question2">question 2
    <button class="option1">1</button>
    <button class="option2 correct">2</button>
    <button class="option3">3</button>
    <button class="option4">4</button>
  </div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

How random option catch correspondent number ?

For example:

  • If question random option is (4) (2) (3) (1) arrangement

  • Answer should be (1),because set class="correct" in question1 option1 but in the case (1) is X (wrong answer).

I guess it get <div> position, so array and real number not match.

What's wrong with my code?



Read more here: https://stackoverflow.com/questions/64402972/how-random-option-catch-correspondent-number

Content Attribution

This content was originally published by Shawn - at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: