Is there a way for me to verify if a dynamic element has an array property with a specific value within its child element?

Seeking assistance to optimize my code and improve my function for a sequence quiz. The objective is to arrange the answers in the correct order and then use a check answers function to validate.

The quiz questions are stored in an array, with each answer having a {"correct_order" :1} property assigned to it. I am now looking for guidance on how to determine if {"correct_order" :1} exists within the answerOneContainer. Below is the relevant HTML markup for the quiz container, the complete JS script, and my attempt at verifying the presence of {"correct_order" :1} inside the // CHECK ANSWER FUNCTION, although I'm uncertain about the correct implementation:

Answer №1

Your code contains numerous errors, making it challenging to understand your intended outcome.

To assist you better, I have made some revisions in order to present a concise and reproducible example ().

It is crucial that you provide runnable code for testing purposes (). Additionally, consider utilizing the "code snippet" feature when editing your answer.

// UPDATES
    const question = document.getElementById('query');
    const choiceOne = document.getElementById('option1');
    const choiceTwo = document.getElementById('option2');
    const choiceThree = document.getElementById('option3');
    const choiceFour = document.getElementById('option4');
    const choiceFive = document.getElementById('option5');

    // QUESTION SET

    const questionsList = [
    {
    query: "Arrange these countries by total population",
    options: [
        { "correct_order": 5, "details": "Ireland" },
        { "correct_order": 2, "details": "United States" },
        { "correct_order": 3, "details": "Russia" },
        { "correct_order": 1, "details": "China" },
        { "correct_order": 4, "details": "United Kingdom" }
    ]
    },
    {
    query: "Sort these countries by size",
    options: [
        { "correct_order": 2, "details": "Canada" },
        { "correct_order": 5, "details": "Ireland" },
        { "correct_order": 3, "details": "Australia" },
        { "correct_order": 4, "details": "Mexico" },
        { "correct_order": 1, "details": "Russia" }
    ]
    },
    {
    query: "Rank these languages by number of speakers",
    options: [
        { "correct_order": 2, "details": "English" },
        { "correct_order": 5, "details": "Arabic" },
        { "correct_order": 3, "details": "Hindustani" },
        { "correct_order": 4, "details": "Spanish" },
        { "correct_order": 1, "details": "Mandarin Chinese" }
    ]
    }
    ]

    // CREATE QUIZ FUNCTION

    document.getElementById("initiate-quiz").onclick = generateQuiz;

    let index = 0;

    function generateQuiz() {
    document.getElementById("prompt").classList.add("d-none");
    document.getElementById("exam").classList.remove("d-none");
    question.innerHTML = questionsList[index].query;
    choiceOne.innerHTML = questionsList[index].options[0].details;
    choiceTwo.innerHTML = questionsList[index].options[1].details;
    choiceThree.innerHTML = questionsList[index].options[2].details;
    choiceFour.innerHTML = questionsList[index].options[3].details;
    choiceFive.innerHTML = questionsList[index].options[4].details;    
    };
    
    // ALTER OPTIONS FUNCTION

    let optionContainers = {
      container1: choiceOneContainer,
      container2: choiceTwoContainer,
      container3: choiceThreeContainer,
      container4: choiceFourContainer,
      container5: choiceFiveContainer
    }

    function switchOptionsContainer(toggleButton, box1, box2) {
    document.getElementById(toggleButton).addEventListener('click', () => {
      $("#" + box1).children(":first").slideToggle('fast');
      $("#" + box2).children(":first").slideToggle('fast', function () {
          optionContainers[box2].appendChild(optionContainers[box1].firstElementChild);
          optionContainers[box1].appendChild(optionContainers[box2].firstElementChild);
      });
      $("#" + box1).children(":first").slideToggle('fast');
      $("#" + box2).children(":first").slideToggle('fast');
      });
    }

    switchOptionsContainer("toggle1", "container1", "container2");
    switchOptionsContainer("toggle2", "container2", "container3");
    switchOptionsContainer("toggle3", "container3", "container4");
    switchOptionsContainer("toggle4", "container4", "container5");

    // VERIFY ANSWER FUNCTION

    document.getElementById("confirmSelection").onclick = validateAnswer;

    function validateAnswer() {
      document.getElementById("confirmSelection").classList.add("d-none");
      document.getElementById("nextQuery").classList.remove("d-none");
      let points = 0;
      if (choiceOneContainer.firstElementChild["correct_order"] === "1") {
      document.getElementById("container1").classList.add("green-border")
      } else {
      document.getElementById("container1").classList.add("red-border")
      }
    };

    // GO TO NEXT QUESTION FUNCTION

    document.getElementById("nextQuery").onclick = nextQuestionButton;

    function nextQuestionButton() {
      if (index >= questionsList.length) {
        index = 0;
        return;
      }
      index++;
      generateQuiz();
      document.getElementById("nextQuery").classList.add("d-none");
      document.getElementById("confirmSelection").classList.remove("d-none");
    };
<div id="exam" class="questionnaire-box d-none">
    <div id="query" class="quizzical-inquiry"></div>
    <div id="container1" class="option-holder">
        <div id="option1" class="selection"></div>
    </div>
    <div class="button-zone">
        <button id="toggle1" class="btn-pattern"><i class="fas fa-sync exchange-trigger"></i></button>
    </div>
    <div id="container2" class="option-holder">
        <div id="option2" class="selection"></div>
    </div>
    <div class="button-zone">
        <button id="toggle2" class="btn-pattern"><i class="fas fa-sync exchange-trigger"></i></button>
    </div>
    <div id="container3" class="option-holder">
        <div id="option3" class="selection"></div>
    </div>
    <div class="button-zone">
        <button id="toggle3" class="btn-pattern"><i class="fas fa-sync exchange-trigger"></i></button>
    </div>
    <div id="container4" class="option-holder">
        <div id="option4" class="selection"></div>
    </div>
    <div class="button-zone">
        <button id="toggle4" class="btn-pattern"><i class="fas fa-sync exchange-trigger"></i></button>
    </div>
    <div id="container5" class="option-holder">
        <div id="option5" class="selection"></div>
    </div>
    <button id="confirmSelection" class="submit-button btn btn-primary btn-lg">Verify Answer</button>
    <button id="nextQuery" class="submit-button btn btn-primary btn-lg d-none">Next Question</button>
    <button id="initiate-quiz" class="submit-button btn btn-primary btn-lg d-none">Start Quiz</button>
</div>

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

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

Error: Angular router outlet could not find any matching routes for the requested

I have been working on an application that utilizes lazy-loaded modules for each main section of the app. In one module, I have two router outlets - a primary one and one called details. const routes: Routes = [ { path: '', component: BooksCo ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...

Exploring Vue Components Through the Global Scope

Is it feasible to retrieve an instantiated Vue.js component object from the global JavaScript scope with Vue.js, or are these objects encapsulated within Vue's internals? For instance, when I have code defining a component like this: Vue.component(&a ...

Node is throwing a 302 error on Localhost:3000

Looking for some guidance as a beginner trying to create and run a nodejs application. Encountering an error while running server.js via nodemon, the console displays the following: Express server listening on port 3000 Mongoose default connection open t ...

Transmit and exchange events between two JavaScript files within a node.js environment

Having some trouble getting EventEmitter to work in both directions between two Javascript files. In my server.js file: let api = require('./api') // Not working api.on("yo", data => { console.log(data) }) // Working api.emit("ready", "S ...

Retrieve worldwide data for the entire application in Next.js during the first page load

Within my Next.js application, I am implementing search filters that consist of checkboxes. To display these checkboxes, I need to retrieve all possible options from the API. Since these filters are utilized on multiple pages, it is important to fetch the ...

Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of ...

Is the return type for EvaluateJavaScript restricted to only String values?

One of the challenges I faced was creating a common function in Kotlin that could invoke a JavaScript function based on the command provided. fun evaluateJsFromNative(command: String, webView: WebView, function: (value : String) -> Unit ) ...

Angular 2 Error: Unable to access the property 'value' as it is undefined

Whenever I click on the Submit button, this error pops up in the browser console. https://i.sstatic.net/57a5N.jpg In my application, I am attempting to retrieve information about the code uploaded by a Student. I am at a loss as to why this error is bein ...

Faulty Image Generated from Matrix Multiplication

I am working with an image matrix that I need to scale down and then back up to its original values. The first step is to read the image into an array of size (150,200,3). image_data = ndimage.imread(image_file,mode='RGB').astype(float) After ...

The error message "Unable to retrieve property 'commands' of undefined (discord.js)" indicates that the specified property is not defined

As I try to incorporate / commands into my Discord bot, I encounter a persistent error: An issue arises: Cannot read property 'commands' of undefined Below is my main.js file and the problematic segment causing the error: Troublesome Segment c ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

Hover over to reveal the text

Would it be feasible to implement JavaScript so that when hovering over or clicking on a word on a webpage, the word can be captured in a variable? I am interested in creating a Firefox extension with this functionality. ...

Using JSON to interact with Response APIs across various programming languages

I am currently facing an issue while attempting to return a response from my API in the language selected from the header using: Accept-Language: es-MX or Accept-Language: en-US function getLanguage(req, res, next) { let lang = req.acceptsLanguages(&a ...

The updateDoc function does not allow for using a variable as a field name

I am currently using the updateDoc function from Firestore and VueJs as my framework. I am attempting to create a nested document with the user input (member_name) as a field name. However, I am encountering an error stating "Unexpected keyword 'this& ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...