简体   繁体   中英

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!!

You can't really do this using the id property. You can however use the value property.

You'd then need to modify the score field. I don't think I saw anywhere where you did that.

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!");
  }
}

I agree with using radio buttons and value. You can easily calculate the score like so:

var score = $('input:checked[value=correct]').length

See example here: https://jsfiddle.net/wLxr3ooq/

Note: If you change "value" to "id" it still works... but you should avoid having duplicate IDs

I think the problem is that you are assigning the same ID to more than one element, which is not allowed. Instead, you can assign them classes. So in your case, assign a class wrong and a class correct to your respective elements. Then, in your JavaScript, try the following

var x = document.getElementsByClassName("correct");

This will grab all the elements with the class correct and return them in an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM