user6442393 user6442393 - 6 months ago 60
HTML Question

Trying to show score on simple HTML and JavaScript Trivia game

Completely new to Javascript and jQuery. I'm building this Trivia quiz with HTML, CSS and Javascript/jQuery and have run into issues.

Here's my complete code - https://jsfiddle.net/CeeSt/8wLj1pk2/ for reference.

Here's a snippet of my HTML and JS -

<div class="question">Question1?
<ul class="answers">
<li><label><input name="Question0" id="correct" type="checkbox"> Answer1</label></li>
<li><label><input name="Question0" id="wrong" type="checkbox"> Answer2</label></li>
<li><label><input name="Question0" id="wrong" type="checkbox"> Answer3</label></li>
</ul>
</div>


JS file -

var score = 0;

function Results() {
if (document.getElementById("correct").checked === true) score++;
else (alert("Incorrect!"));

}


Specifically, I am trying to have the score total displayed in some fashion and am at a loss. I know it's recognizing the 'correct' answer, but showing this as the quiz progresses is what I am struggling with. I know there is likely a better way to do this in pure JavaScript, but if there is any way to salvage this method, please help! Thank you!!

Answer

You should convert these to radio buttons and then evaluate the selected radio button to check whether it is correct:

<div class="question">Question1?
  <ul class="answers">
    <li><label><input name="Question0" value="correct" type="radio"> Answer1</label></li>
    <li><label><input name="Question0" value="wrong" type="radio"> Answer2</label></li>
    <li><label><input name="Question0" value="wrong" type="radio"> Answer3</label></li>
  </ul>
</div>

and your JS would look something like:

var score = 0;

function Results() {
  if ($("input[name=Question0]:checked").val() == "correct") {
    score++;
  } else {
    alert("Incorrect!");
  }
}