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 locate child components without needing to designate the higher-order component encompassing them?

When working with Material-ui, I often find that its extensible nature can be a hindrance when it comes to testing. For example, even if I am using the following code: const MyEventButton = () => (<IconButton /> <Event /> </IconButton ...

Troubleshooting: Why is Angular2 ngClass malfunctioning?

I am having trouble adding a class based on a condition <tr *ngFor="let time of times; let i = index"> <td [ngClass]="{'red-time':checkInvalid(time['Proles Arrive'])}">{{time['Proles Arrive']}}</td& ...

When attempting to install an npm package from a local directory, I encountered a 404 Not Found error, despite the package existing in the node_modules directory

After installing an npm package from a local directory, I noticed that the package was successfully installed and is located in the node_modules directory. However, upon trying to access the package, I encountered the following error: 404 not found I a ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...

"Filtering a JSON File Based on Button Data Attributes: A Step-by-

I am working with a set of buttons that have specific data-map attributes as shown below: <button class="btn btn-default mapper" data-map="2015-11-13">Monday</button> <button class="btn btn-default mapper" data-map="2015-11-14">Tuesday&l ...

Guide to binding input type= 'email' in Knockout.js

My project utilizes KnockoutJS with MVC. I am seeking assistance on determining whether an emailId is valid or invalid. Based on this validation, I need to dynamically enable/disable a button and set an error title for the corresponding textbox. Below is ...

The component data fails to reflect the updated value following a status change due to not properly retrieving the new result from the POST function

Below is the Vue.js 2 code snippet for sending data to the backend. The vuex library was used to manage the data status. After using the POST function, the result returned from the backend updates the value of sampleId. This value is auto-generated by the ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

Update the color of the angular material input text box to stand out

Hey there, I'm currently using Angular Material and I want to change the color of the input focus when clicked. At the moment, it's displaying in purple by default, but I'd like it to be white instead. https://i.stack.imgur.com/vXTEv.png ...

Code - Capture user's input

I have multiple input fields in my HTML document and I want to retrieve the text entered into one of them. Here's an example of one such input field: <TH> <FORM> <input name="designation" type="text" size="12" /> < ...

The location layer on my Google Maps is not appearing

For a school project, I am working on developing a mobile-first website prototype that includes Google Maps integration. I have successfully added a ground overlay using this image, but I am facing issues with enabling the "my location layer". When I tried ...

I am having trouble with Node.js not properly handling POST requests and instead throwing a 505 error

I am a newcomer to nodejs and facing a roadblock in completing my project. I have been stuck for almost 2 days trying to resolve an issue with POST requests not being listened to by nodejs. Despite console logging, I keep getting a 405 error page. Here&ap ...

modify the appearance of HTML controls in real time with C#

Is there a way to dynamically add an additional navigation item to my website's menu list when the admin logs in through admin.aspx? The menu list is created using HTML controls such as <ul>...<li>, and I would like the new navigation item ...

Experiencing difficulties in transmitting images/files to API through reactjs and Material UI upload component

Recently, I tackled the task of creating an image upload component by utilizing an upload component from Material UI. While I have experience with this process using a simple HTML file input in the past, I found myself feeling a bit perplexed this time aro ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

What is the best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

Adjusting the size and adding ellipsis to the <td> component within a table

How can I set a fixed width for td elements in a table and use text-overflow: ellipsis to truncate the text inside the cells? I have attempted various methods without success. Can someone provide guidance on how to achieve this? <table> <tr& ...

The Concept of Interface Segregation Principle within jQuery

Could someone provide a clear explanation of how this function operates using jQuery? Especially in reference to the response found here. It seems similar to the Single Responsibility Principle (SRP) in Object-Oriented Programming. What sets it apart? ...