0

I am creating a math quiz using JavaScript, CSS, and HTML.

I need to display a message to the user saying if they got the answer right or wrong before moving on to the next question. I got it to work for Question 1, which is a text input question. I can't figure out how to do it for Question #2, which is a multiple choice question.

function myAnswer1() {
  let question1 = document.querySelector("#textbox").value;
  if (question1 == 4) {
    alert("You are correct!");
  } else {
    alert("Wrong answer!");
  }
}

function myAnswer2() {
  let question2 = document.querySelector("#mc1").value;

  if (question2 == 9) {
    alert("You are correct!");
  } else {
    alert("Wrong answer!");
  }
}

function myFunction1() {
  document.getElementById("q1").style.display = "block";
}

function myFunction2() {
  document.getElementById("q2").style.display = "block";
  document.getElementById("q1").style.display = "none";
}
<h1>Take the Quiz!</h1>

<form id="quiz" name="quiz">
  <div id="q1">
    <p class="questions">1) What is 2 + 2?</p>
    <input id="textbox" type="text" name="question1" />
    <input type="button" onclick="myAnswer1()" value="Submit Answer" />
  </div>

  <input type="button" onclick="myFunction1()" value="Start Question 1" />

  <div id="q2">
    <p class="questions">2) What is 3 to the power of 2?</p>
    <input type="radio" id="mc1" name="question2" value="9" />9<br />
    <input type="radio" id="mc2" name="question2" value="6" />6<br />
    <input type="radio" id="mc3" name="question2" value="3" />3<br />
    <input type="button" onclick="myAnswer2()" value="Submit Answer" />
  </div>

  <input type="button" onclick="myFunction2()" value="Start Question 2" />
</form>
grooveplex
  • 2,492
  • 4
  • 28
  • 30
Blu
  • 9
  • 3
  • You should look into this question. https://stackoverflow.com/questions/9618504/how-to-get-the-selected-radio-button-s-value – ChrisG Oct 16 '19 at 15:54
  • Some general feedback, if I may: you might want to treat questions as *data*. So, for instance, the first question could be represented by `{q: "What is 2 + 2?", a: 4}` and the second `{q: "What is 3 to the power of 2?", a: 9, choices: [9, 6, 3]}`. I hope that helps :) – grooveplex Oct 16 '19 at 16:29

1 Answers1

0

Replace this:

let question2 = document.querySelector("#mc1").value; 

With this:

let question2 = document.querySelector('input[name="question2"]:checked').value;

Have Fun!

Shlomtzion
  • 674
  • 5
  • 12