Diaz
Diaz

Reputation: 23

Calculating Score for JavaScript Quiz

I'm trying to make a quiz, but I'm having trouble displaying the score.

I used radio buttons with values, either being 0 for wrong answers or 25 for the correct answer. I'm having trouble displaying the score. Here's what I have so far (HTML & Javascript).

function resultScore() {
  result = 0;
  var ans1 = document.getElementById("q1").value;
  var ans2 = document.getElementById("q2").value;
  var ans3 = document.getElementById("q3").value;
  var ans4 = document.getElementById("q4").value;

  result += ans1 + ans2 + ans3 + ans4;



}
<form id="form1">
  <h1> Quiz:</h1>
  <p id="question">Which is mechanical engineering?</p>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Study, design and application of equipment, devices and systems which use electricity, electronics, and electromagnetism.</label>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Computer</label>
  <input type="radio" class="answer" value="25" id="q1" name="choice1" /> study that uses engineering physics, engineering mathematics, and materials science principles to design, analyze, manufacture, and maintain mechanical systems</label>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Study of wild animals</label>

  <p id="question">Who is Nikola Tesla?</p>
  <input type="radio" class="answer" value="25" id="q2" name="choice2" />Serbian-American inventor, electrical engineer, mechanical engineer</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />A method to join strings.</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />Allows you to store information so it can be reused throughout the program</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />Allows you to make a decision based on a condition.</label>

  <p id="question">Who developed de Laval nozzle?</p>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Edith Clarke</label>
  <input type="radio" class="answer" value="25" id="q3" name="choice3" />Gustaf de Laval</label>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Thomas Edison</label>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Alexander Graham Bell</label>

  <p id="question">Who is invented the first iridescent lightbulb?</p>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Edith Clarke</label>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Benjamin Franklin</label>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Claude Shannon</label>
  <input type="radio" class="answer" value="25" id="q4" name="choice4" />Thomas Edison</label>

  <button type="submit" value="Submit" onclick="resultScore()">Submit</button>
  <h2 class="score" id="userScore"> Score: </h2>

Upvotes: 2

Views: 151

Answers (5)

Sunil Chaudhary
Sunil Chaudhary

Reputation: 4743

  • Please don't use same ids for multiple elements. Instead use names to get all the radio elements; then loop and the see if the variable is checked and get the value.
  • ParseInt the values to integers because while getting the values from the elements, they come as string.
  • (Not relevant to calculation part) But as a good practice, please have start tag also if you are having the end tag (see label tag in your html).

Have fixed the solution for you

function getSelectedValue(name) {
    var ele = document.getElementsByName(name);
    for (i = 0; i < ele.length; i++) {
        if (ele[i].checked) {
            return parseInt(ele[i].value) || 0
        }
    }
    return 0 //This will avoid NaN condition incase nothing is selected
}
function resultScore() {
    result = 0;
    var ans1 = getSelectedValue("choice1");
    var ans2 = getSelectedValue("choice2");
    var ans3 = getSelectedValue("choice3");
    var ans4 = getSelectedValue("choice4");
    result += ans1 + ans2 + ans3 + ans4;
    document.getElementById("userScore").innerHTML = "Score: " + result
}
<form id="form1">
  <h1> Quiz:</h1>
  <p id="question">Which is mechanical engineering?</p>
  <label><input type="radio" class="answer" value="0" name="choice1" />Study, design and application of equipment, devices and systems which use electricity, electronics, and electromagnetism.</label>
  <label><input type="radio" class="answer" value="0" name="choice1" />Computer</label>
  <label><input type="radio" class="answer" value="25" name="choice1" /> study that uses engineering physics, engineering mathematics, and materials science principles to design, analyze, manufacture, and maintain mechanical systems</label>
  <label><input type="radio" class="answer" value="0" name="choice1" />Study of wild animals</label>

  <p id="question">Who is Nikola Tesla?</p>
  <label><input type="radio" class="answer" value="25" name="choice2" />Serbian-American inventor, electrical engineer, mechanical engineer</label>
  <label><input type="radio" class="answer" value="0" name="choice2" />A method to join strings.</label>
  <label><input type="radio" class="answer" value="0" name="choice2" />Allows you to store information so it can be reused throughout the program</label>
  <label><input type="radio" class="answer" value="0" name="choice2" />Allows you to make a decision based on a condition.</label>

  <p id="question">Who developed de Laval nozzle?</p>
  <label><input type="radio" class="answer" value="0" name="choice3" />Edith Clarke</label>
  <label><input type="radio" class="answer" value="25" name="choice3" />Gustaf de Laval</label>
  <label><input type="radio" class="answer" value="0" name="choice3" />Thomas Edison</label>
  <label><input type="radio" class="answer" value="0" name="choice3" />Alexander Graham Bell</label>

  <p id="question">Who is invented the first iridescent lightbulb?</p>
  <label><input type="radio" class="answer" value="0" name="choice4" />Edith Clarke</label>
  <label><input type="radio" class="answer" value="0" name="choice4" />Benjamin Franklin</label>
  <label><input type="radio" class="answer" value="0" name="choice4" />Claude Shannon</label>
  <label><input type="radio" class="answer" value="25" name="choice4" />Thomas Edison</label>

  <button type="button" value="Submit" onclick="resultScore()">Submit</button>
  <h2 class="score" id="userScore"> Score: </h2>

Hope it helps. Revert for any clarifications

Upvotes: 0

Bibberty
Bibberty

Reputation: 4768

Use a querySelectorAll to get your selected answers, map the value and convert to int using parseInt and then reduce to add.

presto, this will work with more or less questions.

function resultScore() {

  const result = Array.from(document.querySelectorAll("input[type='radio']:checked"))
                      .map(({ value }) => parseInt(value))
                      .reduce((a,v) => a+v, 0);
  console.log(result);
  document.querySelector('.score').innerHTML = result;

}
  <h1> Quiz:</h1>
  <p id="question">Which is mechanical engineering?</p>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Study, design and application of equipment, devices and systems which use electricity, electronics, and electromagnetism.</label>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Computer</label>
  <input type="radio" class="answer" value="25" id="q1" name="choice1" /> study that uses engineering physics, engineering mathematics, and materials science principles to design, analyze, manufacture, and maintain mechanical systems</label>
  <input type="radio" class="answer" value="0" id="q1" name="choice1" />Study of wild animals</label>

  <p id="question">Who is Nikola Tesla?</p>
  <input type="radio" class="answer" value="25" id="q2" name="choice2" />Serbian-American inventor, electrical engineer, mechanical engineer</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />A method to join strings.</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />Allows you to store information so it can be reused throughout the program</label>
  <input type="radio" class="answer" value="0" id="q2" name="choice2" />Allows you to make a decision based on a condition.</label>

  <p id="question">Who developed de Laval nozzle?</p>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Edith Clarke</label>
  <input type="radio" class="answer" value="25" id="q3" name="choice3" />Gustaf de Laval</label>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Thomas Edison</label>
  <input type="radio" class="answer" value="0" id="q3" name="choice3" />Alexander Graham Bell</label>

  <p id="question">Who is invented the first iridescent lightbulb?</p>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Edith Clarke</label>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Benjamin Franklin</label>
  <input type="radio" class="answer" value="0" id="q4" name="choice4" />Claude Shannon</label>
  <input type="radio" class="answer" value="25" id="q4" name="choice4" />Thomas Edison</label>

  <button onclick="resultScore()">Submit</button>
  <h2 class="score" id="userScore"> Score: </h2>

Upvotes: 1

Goran Stoyanov
Goran Stoyanov

Reputation: 2311

In short:

  1. Change the button type to button not submit as the latter refreshes the page and the js function is not executed.
  2. Set the score content with the calculated result.
  3. I've used parseInt() to parse the value from string to int before doing the calculation.

function resultScore() {
  result = 0;
  var ans1 = parseInt(document.querySelector('input[name="choice1"]:checked')?document.querySelector('input[name="choice1"]:checked').value:0);
  var ans2 = parseInt(document.querySelector('input[name="choice2"]:checked')?document.querySelector('input[name="choice2"]:checked').value:0);
  var ans3 = parseInt(document.querySelector('input[name="choice3"]:checked')?document.querySelector('input[name="choice3"]:checked').value:0);
  var ans4 = parseInt(document.querySelector('input[name="choice4"]:checked')?document.querySelector('input[name="choice4"]:checked').value:0);

  result = ans1 + ans2 + ans3 + ans4;
  
  const score = document.querySelector(".score");
  score.innerHTML = `Score: ${result}`;

}
<form class="form1">
  <h1> Quiz:</h1>
  <p class="question">Which is mechanical engineering?</p>
  <input type="radio" class="answer" value="0" name="choice1" />Study, design and application of equipment, devices and systems which use electricity, electronics, and electromagnetism.</label>
  <input type="radio" class="answer" value="0" name="choice1" />Computer</label>
  <input type="radio" class="answer" value="25" name="choice1" /> study that uses engineering physics, engineering mathematics, and materials science principles to design, analyze, manufacture, and maintain mechanical systems</label>
  <input type="radio" class="answer" value="0" name="choice1" />Study of wild animals</label>

  <p class="question">Who is Nikola Tesla?</p>
  <input type="radio" class="answer" value="25" name="choice2" />Serbian-American inventor, electrical engineer, mechanical engineer</label>
  <input type="radio" class="answer" value="0" name="choice2" />A method to join strings.</label>
  <input type="radio" class="answer" value="0" name="choice2" />Allows you to store information so it can be reused throughout the program</label>
  <input type="radio" class="answer" value="0" name="choice2" />Allows you to make a decision based on a condition.</label>

  <p class="question">Who developed de Laval nozzle?</p>
  <input type="radio" class="answer" value="0" name="choice3" />Edith Clarke</label>
  <input type="radio" class="answer" value="25" name="choice3" />Gustaf de Laval</label>
  <input type="radio" class="answer" value="0" name="choice3" />Thomas Edison</label>
  <input type="radio" class="answer" value="0" name="choice3" />Alexander Graham Bell</label>

  <p class="question">Who is invented the first iridescent lightbulb?</p>
  <input type="radio" class="answer" value="0" name="choice4" />Edith Clarke</label>
  <input type="radio" class="answer" value="0" name="choice4" />Benjamin Franklin</label>
  <input type="radio" class="answer" value="0" name="choice4" />Claude Shannon</label>
  <input type="radio" class="answer" value="25" name="choice4" />Thomas Edison</label>

  <button type="button" value="Submit" onclick="resultScore()">Submit</button>
  <h2 class="score" class="userScore"> Score: </h2>

EDIT:

  1. I've changed multiple identical id attributes to classes and used the name attribute for selecting radio buttons.

  2. Also, validation is added if the radios are not selected.

Upvotes: 1

mplungjan
mplungjan

Reputation: 178412

  • You need to not submit - I use preventDefault and the submit event instead of click
  • You need to convert the values to number (I use +)
  • You need to loop over all checked radios
  • You cannot have duplicate IDs

window.addEventListener("load", function() { // when page loaded
  document.getElementById("form1").addEventListener("submit", function(e) { // when submitted
    e.preventDefault(); // cancel submit
    result = 0;
    [...document.querySelectorAll(".answer:checked")] // all checked radios
     .forEach(rad => result += +rad.value); // add their numeric value
    document.getElementById("userScore").innerHTML = result;
  })
})
<form id="form1">
  <h1> Quiz:</h1>
  <p id="question">Which is mechanical engineering?</p>
  <input type="radio" class="answer" value="0" name="choice1" />Study, design and application of equipment, devices and systems which use electricity, electronics, and electromagnetism.</label>
  <input type="radio" class="answer" value="0" name="choice1" />Computer</label>
  <input type="radio" class="answer" value="25" name="choice1" /> study that uses engineering physics, engineering mathematics, and materials science principles to design, analyze, manufacture, and maintain mechanical systems</label>
  <input type="radio" class="answer" value="0" name="choice1" />Study of wild animals</label>

  <p id="question">Who is Nikola Tesla?</p>
  <input type="radio" class="answer" value="25" name="choice2" />Serbian-American inventor, electrical engineer, mechanical engineer</label>
  <input type="radio" class="answer" value="0"  name="choice2" />A method to join strings.</label>
  <input type="radio" class="answer" value="0"  name="choice2" />Allows you to store information so it can be reused throughout the program</label>
  <input type="radio" class="answer" value="0"  name="choice2" />Allows you to make a decision based on a condition.</label>

  <p id="question">Who developed de Laval nozzle?</p>
  <input type="radio" class="answer" value="0"  name="choice3" />Edith Clarke</label>
  <input type="radio" class="answer" value="25" name="choice3" />Gustaf de Laval</label>
  <input type="radio" class="answer" value="0"  name="choice3" />Thomas Edison</label>
  <input type="radio" class="answer" value="0"  name="choice3" />Alexander Graham Bell</label>

  <p id="question">Who is invented the first iridescent lightbulb?</p>
  <input type="radio" class="answer" value="0"  name="choice4" />Edith Clarke</label>
  <input type="radio" class="answer" value="0"  name="choice4" />Benjamin Franklin</label>
  <input type="radio" class="answer" value="0"  name="choice4" />Claude Shannon</label>
  <input type="radio" class="answer" value="25" name="choice4" />Thomas Edison</label>

  <button type="submit" value="Submit">Submit</button>
  <h2 class="score" id="userScore"> Score: </h2>

Upvotes: 2

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22935

Just get the result dom element and update the content with new score

document.getElementById('userScore').innerHTML = `Score: ${result}`;

Upvotes: -1

Related Questions