Bob
Bob

Reputation: 41

JavaScript quiz answer check up

I'm trying to make a score base quiz where it shows how much score you get when finished e.g. out of 8 and the answers you got incorrect. I have the score system out of the way, just not the validation

HTML

        <div class="quiz">
        1) What noise does a dog make?</div>
        <div class="values">
        <input type="radio" value="0"  id="q1" name="q1" onclick="question('jq1',this.value)">a) Cluck<br>
        <input type="radio" value="0"  id="q1" name="q1" onclick="question('jq1',this.value)">b) Meow<br>
        <input type="radio" value="0"  id="q1" name="q1" onclick="question('jq1',this.value)">c) Moo<br>
        <input type="radio" value="1"  id="q1" name="q1" onclick="question('jq1',this.value)">d) Woof</div><br>
        <input type="hidden" name="jq1" id="jq1" /> 

        <div class="quiz">
        2) What noise does a cat make?</div>
        <div class="values">
        <input type="radio" value="1" id="q2" name="q2" onclick="question('jq2',this.value)">a) Meow<br>
        <input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">b) Cluck<br>
        <input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">c) Woof<br>
        <input type="radio" value="0" id="q2" name="q2" onclick="question('jq2',this.value)">d) Moo</div><br>
        <input type="hidden" name="jq2" id="jq2" />

(sorry for inappropriate questions, they're just there as placeholders :D)

JavaScript

function question(ref,val) { 
    var x = document.getElementById(ref); 
    x.value = val; 
}
function result() { 
    var score = 0; 
    var x = document.getElementById('jq1'); 
    score = eval (score) + eval(x.value); 
    var x = document.getElementById('jq2'); 
    score = eval (score) + eval(x.value);

    alert("You scored: "+score +" out of 2!"); 
}

I'd like a new line underneath the current one in the alert box saying "Questions 1, 2, 3 were incorrect". Just very unsure on how to do this and would like someone's help.

Thanks very much!

Upvotes: 0

Views: 8813

Answers (4)

M Hasan Sunny
M Hasan Sunny

Reputation: 29

Demo:

https://quiz-using-javascript.web.app/

Source Code:

https://github.com/mhsunny/JavaScript-Quiz

This is the project to build a quiz using JavaScript. You can find how to check the answer of questions using javascript forEach() and using setInterval and clearInteval method.

app.js

app.js

const correctAnswers = ['B', 'B', 'B', 'B'];
const form = document.querySelector('.quiz-form');

const result = document.querySelector('.result');


form.addEventListener('submit', e =>{

    e.preventDefault();

    let score = 0;
    const userAnswer = [form.q1.value, form.q2.value,    form.q3.value, form.q4.value]
    //check answers

    userAnswer.forEach((answer, index) =>{

        if(answer === correctAnswers[index]){
            score +=25;
        }
      //  console.log(score);
      //show result on page

    });

    scrollTo(0, 0);
    result.classList.remove('d-none');
    let output = 0;
    const timer = setInterval(()=>{
        result.querySelector('span').textContent = `${output}%`;
        if(output === score){
            clearInterval(timer);
        }else{
            output++;
        }
    }, 10)

})

// let i = 0; 
// const timer = setInterval(()=>{
//     console.log("hello")
//     i++;
//     if(i == 5){
//         clearInterval(timer);
//     }
// }, 1000)

index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> JavaScript Quiz</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>

    <!-- top section -->
    <div class="intro py-3 bg-white text-center">
        <div class="container">
            <h2 class="text-primary display-3 my-4"> Quiz using Javascript</h2>
        </div>
    </div>


    <!-- result section -->
    <div class="result py-4 d-none bg-light text-center">
        <div class="container lead">
            <p>You are <span class="text-primary display-4 p-3">0%</span> ninja</p>
        </div>
    </div>

    <!-- quiz section -->
    <div class="quiz py-4 bg-primary">
        <div class="container">
            <h2 class="my-5 text-white">On with the questions...</h2>

            <form class="quiz-form text-light">
                <div class="my-5">
                    <p class="lead font-weight-normal">1. How do you give a ninja directions?</p>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q1" value="A" checked>
                        <label class="form-check-label">Show them a map</label>
                    </div>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q1" value="B">
                        <label class="form-check-label">Don't worry, the ninja will find you</label>
                    </div>
                </div>
                <div class="my-5">
                    <p class="lead font-weight-normal">2. If a ninja has 3 apples, then gives one to Mario & one to Yoshi, how many apples does the ninja have left?</p>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q2" value="A" checked>
                        <label class="form-check-label">1 apple</label>
                    </div>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q2" value="B">
                        <label class="form-check-label">3 apples, and two corpses</label>
                    </div>
                </div>
                <div class="my-5">
                    <p class="lead font-weight-normal">3. How do you know when you've met a ninja?</p>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q3" value="A" checked>
                        <label class="form-check-label">You'll recognize the outfit</label>
                    </div>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q3" value="B">
                        <label class="form-check-label">The grim reaper will tell you</label>
                    </div>
                </div>
                <div class="my-5">
                    <p class="lead font-weight-normal">4. What's a ninja's favourite array method?</p>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q4" value="A" checked>
                        <label class="form-check-label">forEach()</label>
                    </div>
                    <div class="form-check my-2 text-white-50">
                        <input type="radio" name="q4" value="B">
                        <label class="form-check-label">slice()</label>
                    </div>
                </div>
                <div class="text-center">
                    <input type="submit" class="btn btn-light">
                </div>
            </form>

        </div>
    </div>

    <script src="app.js"></script>
</body>

</html>

Upvotes: 0

Vitim.us
Vitim.us

Reputation: 22148

A more object oriented answer

DEMO: http://jsfiddle.net/Victornpb/3cwzndp8/1/

var q = [
    {
        question:"What noise does a dog make?",
        options:["Meow", "Cluck","Woof","Moo"],
        answers: [0,0,1,0]
    },
    {
        question:"What noise does a cat make?",
        options:["Meow", "Cluck","Woof","Moo"],
        answers: [1,0,0,0]
    }
];

var questionary = generateQuestionary(q);
quizBody.appendChild(questionary);

function generateQuestionary(obj){
    var questionary = tag("div",{className:"questionary"});

    for(var i=0; i<obj.length; i++){
        questionary.appendChild(generateQuestionHtml(obj[i], i));
    }
    return questionary;
}

function generateQuestionHtml(obj, n){
    var answers = tag("div",{className:"answers"});

    for(var i=0; i<obj.options.length; i++){
        answers.appendChild(
            tag("label",{},
                tag("input",{type:"radio", name:"q"+n, value:obj.answers[i],onclick:ck} ),
                tag("span",{}, obj.options[i]),
                tag("br")
               )
        );
    }

    return tag("div",{className:"quiz"},
       tag("div",{className:"question"}, obj.question),
       answers,
       tag("div",{className:"info"})
    );
}

function ck(e){
    console.log(this);
    var infoBox = this.parentElement.parentElement.parentElement.getElementsByClassName("info")[0];

    if(this.value==1){
        infoBox.innerHTML = "Correct!";
        infoBox.classList.remove("wrong");
    }
    else{
        infoBox.innerHTML = "Incorrect answer :(";
        infoBox.classList.add("wrong");
    }
}

I used a utility function to generate the DOM Elements (the tag() function)

https://gist.github.com/victornpb/11201998

Upvotes: 1

Vitim.us
Vitim.us

Reputation: 22148

It's not clear what you want to accomplish.

eval is totally unnecessary here, and shouldn't be used.

window.onload = function() {
  check.onclick = result;
}

function result() {
  var score = 0;
  score += parseInt(getSelectedRadioValue("q1")) || 0;
  score += parseInt(getSelectedRadioValue("q2")) || 0;

  alert("You scored: " + score + " out of 2!");
}


function getSelectedRadioValue(name) {
  var radios = document.getElementsByName(name);
  for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
      return radios[i].value;
    }
  }
}
<div class="quiz">
  1) What noise does a dog make?</div>
<div class="answers">
  <label>
    <input type="radio" value="0" name="q1">a) Meow</label>
  <br>
  <label>
    <input type="radio" value="0" name="q1">b) Cluck</label>
  <br>
  <label>
    <input type="radio" value="1" name="q1">c) Woof</label>
  <br>
  <label>
    <input type="radio" value="0" name="q1">d) Moo</label>
  <br>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />

<div class="quiz">
  2) What noise does a cat make?</div>
<div class="answers">
  <label>
    <input type="radio" value="1" name="q2">a) Meow</label>
  <br>
  <label>
    <input type="radio" value="0" name="q2">b) Cluck</label>
  <br>
  <label>
    <input type="radio" value="0" name="q2">c) Woof</label>
  <br>
  <label>
    <input type="radio" value="0" name="q2">d) Moo</label>
  <br>
</div>
<br>
<input type="hidden" name="jq2" id="jq2" />

<input type="button" id="check" value="I'm done">

Upvotes: 0

Harris
Harris

Reputation: 1785

Assuming you want a rudimentary, client-side system, I would suggest declaring an object that holds the answers when the page loads, with the name of each group of choices as the key, and the correct answers being the values.

Say that question 1, labeled "q1", has 3 choices, the answer being the first.

var answers = {q1:0, q2:3}; 
//The key "q1" gets the value 0, while "q2" will get 3 (or any arbitrary value you want)

Now you can say

if(answers["q1"] != document.forms["formNameHere"].elements["q1"].value)
    alert("Everything is awful, you got question one wrong");

You can iterate through each question, checking if the answer is correct, and assembling a string of the wrong answers, which you can display through your alert on a new line.

Upvotes: 0

Related Questions