What is the best way to achieve results through a single button click that includes all existing elements?

I'm in the process of creating a simple and user-friendly Javascript-based quiz application with basic code, not advanced JavaScript. While everything else is functioning properly, I've hit a roadblock when it comes to displaying the results within an HTML tag using JavaScript. Below is my current code:

// To display results in an HTML tag using JavaScript

function check(){
    var score = 0;

    // Question 1
    var q1WriteAnswer = document.getElementById('q1_o3');
    var q1option1 = document.getElementById('q1_o1');
    var q1option2 = document.getElementById('q1_o2');
    var q1option4 = document.getElementById('q1_o4');

    if (q1WriteAnswer.checked == true){
        score++;
    }
    else{
        alert("wrong answer");
    }

    // Repeat for each question...

    var resultTag = document.createElement("h3");
    resultTag.innerText = "Your Score: " + score;
    document.body.appendChild(resultTag);
}

Answer №1

One efficient way to accomplish this task is by utilizing the querySelector method, as demonstrated below:

// Here's a crucial solution in JavaScript for the given problem.

function checkQuestion(questionName, answerID) {
  if (questionName == null || answerID == null) return;

  const answer = document.getElementById(answerID);
  const question = document.querySelector(`input[name="${questionName}"]:checked`);

  if (answer == null || question == null) return;

  return answer.id === question.id;
}

function updateScore(name, score, isCorrect) {
  if (isCorrect == null) return score;

  if (isCorrect) {
    document.querySelectorAll(`input[name="${name}"]:not(:checked)`).forEach(input => input.disabled = true);
    return score + 1;
  } else 
     alert("Incorrect answer");

  return score;
}

function check() {
  let score = 0;

  // Question no1
  const nameQ1 = 'founder';
  const validQ1 = checkQuestion(nameQ1, 'q1_o3');
  score = updateScore(nameQ1, score, validQ1);

  // Repeat the process for the other questions as well...

  // Display the final result
  const ab = document.querySelector('.ab') || ((e) => {
    e.classList.add('ab');
    document.body.appendChild(e);
    return e;
  })(document.createElement("h3"));
  ab.innerText = score;
}
/* Styles for formatting the quiz application UI */

body{
    margin: 1em;
    color: white;
    background-color: #222;
    background-image: url(images/bg.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;

}

fieldset{
    border-radius: 15px;
    text-align: center;
}

h3{
    background-color: cornsilk;
    color: blue;
    width: 10vw;
    height: 5vh;
    text-align: center;
    position: relative;
    left: 45%;
}
input[type=radio]:disabled ~ label {
  color: gray;
}
<h1>Quiz Application</h1>

<!-- Add the quiz questions with radio buttons here -->

<button onclick="check()">Results</button>

Answer №2

The radio input elements needed some adjustments. To ensure better functionality, it is recommended to include a label element below each input with type="radio" and omit the closing radio tag.

To streamline the JavaScript code, you can simplify by verifying if only the right answer is selected. Below, I have provided a code snippet containing the script for reference.

By isolating only the correct answer input elements, you can store them in an array and iterate over the array to determine if the correct answer is chosen.

I have demonstrated an improved method to achieve the desired outcome with an example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Quiz Application</h1>
    <h2>Score: <span id="score">0</span></h2>

    <div>
        <fieldset>Who is the founder of Pakistan? <br>
            <input type="radio" name="founder" id="q1_o1" value="Allama Iqbal">
            <label for="founder">Allama Iqbal</label>
            <input type="radio" name="founder" id="q1_o2" value="Manzoor Kapri">
            <label for="founder">Manzoor Kapri</label>
            <input type="radio" name="founder" id="q1_o3" value="Quaid-e-Azam">
            <label for="founder">Liaquat Ali Jinah</label>
            <input type="radio" name="founder" id="q1_o4" value="Liaquat Ali Jinah">
            <label for="founder">Liaquat Ali Jinah</label>
        </fieldset>

        <fieldset>Who is the national poet of Pakistan? <br>
            <input type="radio" name="national_poet" id="q2_o1" value="Allama Iqbal">
            <label for="national_poet">Allama Iqbal</label>
            <input type="radio" name="national_poet" id="q2_o2" value="Manzoor Kapri">
            <label for="national_poet">Manzoor Kapri</label>
            <input type="radio" name="national_poet" id="q2_o3" value="Quaid-e-Azam">
            <label for="national_poet">Liaquat Ali Jinah</label>
            <input type="radio" name="national_poet" id="q2_o4" value="Liaquat Ali Jinah">
            <label for="national_poet">Liaquat Ali Jinah</label>
        </fieldset>
    </div>

    <button onClick="check()">Check Answer</button>
    

    <script>
        function check(){
            // question no1
            var score = 0;
            var wrong_count = 0;
            var scoreNode = document.getElementById('score');


            const answer1 = document.getElementById('q1_o3');
            const answer2 = document.getElementById('q2_o1');

            const answers = [answer1, answer2];

            answers.forEach(answer => {
                if (answer.checked) {
                    score++
                } else {
                    wrong_count++
                }
            })

            scoreNode.innerHTML = score;

            if (wrong_count > 0) {
                alert(`You answered ${wrong_count} question(s) incorrectly.`);
            }
            
        }
    </script>
</body>
</html>

Answer №3

It appears that there are several errors in your code:

  1. You are mistakenly adding a closing < /radio > tag which is unnecessary
  2. You are repeatedly resetting the sum variable to 0
  3. Your JavaScript code contains logic for 10 questions, but your HTML only has provision for 9 questions
  4. There seems to be an issue with how you are appending elements to the body in your code

// Here is a corrected version of the Javascript code

function check(){
    var score = 0;

    // Question no1
    var q1WriteAnswer = document.getElementById('q1_o3');
    var q1option1 = document.getElementById('q1_o1');
    var q1option2 = document.getElementById('q1_o2');
    var q1option4 = document.getElementById('q1_o4');

    if (q1WriteAnswer.checked==true){
        score++
    }
    else{
        alert("Incorrect answer");
    }

// Repeat similar structure for remaining questions...

var finalScore = document.createElement("h3");
finalScore.innerText = "Your score: " + score;
document.getElementsByTagName('body')[0].appendChild(finalScore);

}
/* CSS Code */
body {
    color: white;
    background-color: #222;
    background-image: url(images/bg.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}

fieldset {
    border-radius: 15px;
    text-align: center;
}

h3 {
    background-color: cornsilk;
    color: blue;
    width: 10vw;
    height: 5vh;
    text-align: center;
    position: relative;
    left: 45%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quiz Application</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <h1>Quiz Application</h1>

    <div>
    <fieldset>
        <p>Who is the founder of Pakistan?</p>
        <input type="radio" name="founder" id="q1_o1">Allama Iqbal
        <input type="radio" name="founder" id="q1_o2">Manzoor Kapri
        <input type="radio" name="founder" id="q1_o3">Quaid-e-Azam
        <input type="radio" name="founder" id="q1_o4">Liaquat Ali Jinah
    </fieldset>
    </div><br>
    
    <!-- Include the remaining HTML code for the quiz questions -->

    <button onclick="check()">Results</button>


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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the dimensions of an HTML5 canvas to fit the page while maintaining a specific size for the image displayed

Currently, I am creating a specific sized image at 1200W x 300H and then sending it back to my server once it's done. The process is functional. However, the issue arises when the created image of 1200x300 size appears too large for many users, espec ...

Using MongoDB to insert multiple documents in a POST endpoint

When trying to insert multiple documents with MongoDB in the same request, I am encountering an issue where I am getting an undefined value. .post(function (req, res) { ... Item.create(data) .then(function (item) { var newOtherItem; ...

What is the recommended approach for effectively cascading the deletion of a secondary object in MongoDB when an account is

My app allows users to create accounts and interact with posts by liking and sharing them. However, I'm facing an issue when a user decides to delete their account. I have managed to resolve most of the related data removal except for one specific cas ...

What steps can be taken to integrate JavaScript into an ASP.NET control?

<script type="text/javascript"> $(document).ready(function () { $('input[name="time"]').ptTimeSelect(); }); </script> the script shown above is functioning correctly with this HTML input: <input name="time" value= ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

Setting a closure to encapsulate a global variable

I possess a set of functions that allow me to configure prompts for when someone exits a page while inputting values. However, my main concern lies in how to properly encapsulate the checkFlag. Currently, checkFlag is being treated as a global variable whi ...

Utilizing multiple API requests within a single Angular service

I am using Angular $http requests to access an API and retrieve information about various football teams. If I were only dealing with one team, it would be simple - I would create a Service that makes the request and then use that function in my controlle ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

Fixed scrollable element positioned at the bottom of the webpage

I’m facing a challenge where I need a scrollable element positioned at the bottom of my webpage. Initially, I tried setting position: fixed along with bottom:0. However, this approach didn’t work for me since I require a horizontal list that can be scr ...

Is there a way to integrate boolean into an if-else statement effectively?

I am currently pondering over the following: Implement a control structure in JavaScript using an if..else statement. Define a variable and use a Boolean condition to determine whether it is true or false. If the condition evaluates to true, execute the ...

Retrieving JSON data using the fetch method in JavaScript

Currently, I am attempting to retrieve a JSON array using AJAX. Upon calling my test.php file, the following content is returned: [{"name":"James","age":24},{"name":"Peter","age":30}] This is the JavaScript code that I am using: var persons = new Array( ...

Template for developing projects using JavaScript, HTML5, and CSS3 in Visual Studio 2013

After recently downloading Visual Studio 2013 Express for Web, I am struggling to figure out how to deploy projects that only consist of JavaScript, HTML5, and CSS3. Despite searching online for JavaScript templates and even trying to download Visual Stu ...

JavaScript code to toggle the navigation bar on mobile devices

I am experiencing an issue with a script that is not performing the desired task. I am looking for a script that can add the Class "active" to a ul element with the id "btnMob0". Currently, my script looks like this: <script type="text/javascript"> ...

Creating random UUIDs in JavaScript

I want to create a function that can generate a random uuid, and I came across some code snippets on Stack Overflow. I need help understanding how this function works in order to implement it using TypeScript: public generateUniqSerial() { return &apos ...

How can we show a React JS component when clicked, without using the App.js file for display?

How can I display a component onclick in React JS without using UseState in a file other than App.js? This code will be in App.js var [clicks, setClicks] = useState(false) return( <> {clicks && &l ...

Tips for adjusting the width of the box-shadow in CSS

I am facing a challenge with my button that has a box-shadow effect on hover. Currently, I am unsure how to adjust the width of the box-shadow effect. Here is a snapshot of my button's current appearance: https://i.stack.imgur.com/Mg0df.png</p&g ...

Guide to creating an intricate formula using the keyup event

Just starting out with coding and I need help making this formula work. GPro = 31 * ((Cr / 8.4)-1.5) * (kA-0.2) * kG I have an online calculator set up to update automatically when the user inputs data (on keyup event). The site has three formulas - Crum ...

"Improving React's state array with real-time data from the Spotify API

We have been working on an interesting task involving populating an array with songs using the Spotify API. Since the API allows fetching 50 songs at a time, we devised a loop implementing an offset to acquire a total of 250 songs. Our aim is to update t ...

AngularJS combined with the power of WebSockets

I am currently working on a project that involves multiple controllers. One of these controllers requires me to establish a web socket connection, while another needs to listen for messages and update the $scope if necessary. Can you please help me by prov ...