Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive.

I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am faced with the task of enabling users to select more than one correct answer for each question. How can I achieve this functionality? Do I simply need to designate multiple correct answers in the JSON file?

Your guidance is greatly appreciated!

Below is a snippet of my code:

HTML:

<!DOCTYPE HTML>

<html ng-app="myQuiz">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test Your Knowledge: Saturn</title>
        <link rel="stylesheet" type="text/css" href="css/quiz.css">
    </head>
    <body>

    ...

JSON (multiple questions included - formatted as shown:

[{
    "question" : "What is the name of Saturn's largest moon?",
    "answers"  : [
        {"id"  : 0, "text" : "Hercules"},
        {"id"  : 1, "text" : "Europa"},
        {"id"  : 2, "text" : "Goliath"},
        {"id"  : 3, "text" : "Zeus"},
        {"id"  : 4, "text" : "Titan"},
        {"id"  : 5, "text" : "Triton"}
    ],
    "correct"  : 4,
    "feedback" : "Though the names seem similar, Triton orbits the planet Neptune."
}]

JavaScript

(function(){
var app = angular.module('myQuiz',[]);
app.controller('QuizController'['$scope','$http','$sce',function($scope,$http,$sce){
...

Answer №1

There are various methods you can employ to solve this problem.

While I could simply provide the solution, I believe there is value in trying to figure it out yourself with some guidance, especially since you mentioned that you are new to this. :)

Here is a suggested approach:

Start by creating a memory store of answers to compare against

  • When a checkbox is selected, compare the question and answer to those stored
  • If the stored question includes the selected answer, you have a match. Otherwise, it's a miss.

For instance:

var questions = {
    "question1": ["answer1", "answer2"],
    "question2": ["answer1", "answer3", "answer3"]
};

function checkAnswer(question, selectedAnswer) {
    if (questions[question]) {
        var found = false;

        questions[question].forEach(function (answer) {
            if (answer === selectedAnswer) {
                found = true;
            }
        });

        if (found) {
            // Perform specific action
        }

        return found;
    }
}

console.log(checkAnswer("question1", "answer1")) // true
console.log(checkAnswer("question1", "answer4")) // false

You can enhance this function further by allowing it to accept multiple answers as input instead of just one, or evaluate all answers for a single question against the stored data. Alternatively, you can apply the same function to each selected answer for a given question. Both approaches are effective.

This should accomplish your objective! :)


If you encounter any difficulties and require assistance, feel free to leave a comment detailing your specific situation (e.g., Angular), and I'll devise a solution tailored to your needs.

Answer №2

Consider updating the "correct" field in your json to an array of ids.

If you have a question with only one answer, the array will contain just one element.

If you have a question with multiple answers, adjust your javascript function selectAnswer() to handle an array instead of a single value.

Quick tip: consider using boolean values for your "correctness" and "answered" fields instead of strings.

Answer №3

Resolved using the code snippet below:

var superbag = function(sup, sub) {
    sup.sort();
    sub.sort();
    var i, j;
    for (i=0,j=0; i<sup.length && j<sub.length;) {
        if (sup[i] < sub[j]) {
            ++i;
        } else if (sup[i] == sub[j]) {
            ++i; ++j;
        } else {
            // sub[j] not in sup, so sub not subbag
            return false;
        }
    }
    // make sure there are no elements left in sub
    return j == sub.length;
}
var contains = function(needle) {
    // Per spec, the way to identify NaN is that it is not equal to itself
    var findNaN = needle !== needle;
    var indexOf;

    if(!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {
                var item = this[i];

                if((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle) > -1;
};

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

Is there a way to use Ajax to analyze and contrast information from two separate web links?

I am looking to compare and display the genre_ids from the first link and the id from the second link. Example: genre_ids: [ 18, 878, ] { id: 18, name: "Drama", }, { id: 878, name: "Science Fiction", } Result: Drama, Science Fiction $(document).ready( ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

Error: Incorrect Path for Dynamic Import

Recently, I've been trying to dynamically load locale files based on the locale code provided by Next.js. Unfortunately, every time I attempt a dynamic import, an error surfaces and it seems like the import path is incorrect: Unable to load translatio ...

Verifying if a div in jQuery holds a specific element

I am currently developing drag and drop widgets using jQuery. After dropping them, I need to verify if my draggable and droppable widget is located inside another div. <div id="droptarget"> <div class="widget">I'm a widget!</div> ...

Tips on choosing additional (sibling) elements with CSS?

My navbar has the following structure: <ul class="nav navbar-nav"> <li class="nav-item"><a href="#services">Services</a></li> <li class="nav-item"><a href="#work">Work</a></li> <li class ...

Conceal the ion-tabs in an ionic framework

I have been implementing a solution to hide ion-tabs by following this codepen example: <ion-tabs ng-class="{'tabs-item-hide': hideTabs}"> // --> my tabs content </ion-tabs> <ion-view hide-tabs> // --> my content ...

Ways to access a global JavaScript object in a separate .js file

How can I access an object that was initialized in my HTML document? This is what my HTML document looks like: ... <script type="text/javascript" id="controller">var controller = false;</script> ... <body onload="controller = ne ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Trouble with Mocha async hooks execution?

I keep encountering the issue of receiving 'undefined' for the page in this setup. It appears that none of Mocha's hooks are being executed. I've attempted adding async to the describe at the top level, used done statements, and even tr ...

Is there a way to eliminate the return?

Struggling to eliminate the unwanted return in my Wordpress loop. The layout is ruined by trying to display a thumbnail next to the entry: Even using padding for the entry made it worse! Here's the code snippet that I have tried: #thumbnai ...

Access in-depth data by clicking on a map to get detailed information

Recently, I took on the challenge of managing a golf club website after the original creator had to step away. One urgent issue I need to address is fixing a malfunctioning flash animation that provides information about each hole on the course. My plan is ...

Is there a way to move the bootstrap carousel item captions outside of the image without having to set a specific height for the carousel manually?

<div id="carouselExampleIndicators" className="carousel slide" data-bs-ride="true"> <div className="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" className="active" ...

Verify the presence of a boolean false value in mustache.js

As stated in this particular query, the method of checking for false within a json object passed to a mustache template is as follows: {{^like}} it is false {{/like}} {{#like}} it is true {{/like}} Assuming our json data appears like this {"like" ...

Error: Invalid Argument - The argument 'PanelController' is expected to be a function, but it is undefined

Here is a snippet of my HTML code: <body ng-controller="StoreController as store"> ........... <section ng-controller="PanelController as panel"> <ul class="nav nav-pills""> <li ng-class="{active:panel.isSe ...

Implement a dispatcher in raw JavaScript using React combined with the Redux Toolkit package

In my React app, I have been using Redux and Redux Toolkit within React components by utilizing the useDispatch and useSelector hooks. However, I now need to update the Redux store from a pure JavaScript module that interacts with IndexedDB to save user da ...

Refresh the block's content seamlessly without the need for a page reload

Within the index.html page There exists a block called content that contains various content blocks. An additional navigation menu with numerous links is present. It is important that when you click on a menu link, the content within the content block re ...

Having trouble executing multiple file uploads with node.js resulting in an ERR_EMPTY_RESPONSE?

Currently, I am attempting to upload multiple files on FTP using node.js. Everything seems to be going smoothly as the files are successfully uploaded to the server location. However, after some time passes, I do not receive a success message. Instead, I e ...

Troubleshoot some PHP script

I am having an issue while attempting to create a login system using angularjs and PHP. I am encountering a problem that I cannot seem to grasp the reason behind? <?php date_default_timezone_set("Asia/Bangkok"); session_start(); $data = json_decode(fi ...

Is there a way to retrieve the current logged in user when working with socket.io?

When it comes to retrieving the logged in user using passport.js in most of my routes, it's a breeze - just use req.user.username. However, I've encountered an issue with a page that relies solely on websockets. How can I determine the username o ...

The function request.raw_post is returning a null value after sending a webhook

I am currently working on an application that receives webhooks from GitHub. The process involves obtaining the raw data and parsing it as shown below: raw_payload = request.raw_post original_payload = JSON.parse(raw_payload) The variable original_payloa ...