Organizing quiz inquiries within an array of objects

I'm currently working on developing a JavaScript quiz program. All of the questions are stored in an array, with each question being represented as an object containing the question itself, answer choices for the user to select from, and the correct answer. The goal is to loop through the array of questions and display each question with radio buttons for the user to choose their answer. However, I'm facing challenges in populating these radio buttons with the text of the answer choices. Any suggestions on how to achieve this?

      var userChoices = document.getElementsByTagName('input[type:radio]');
      var questions = 
      [
        {
          question: "Who wrote 'Harry Potter'?",
          choices: ["J.K. Rowling", "Stephen King", "George Orwell", "Jane Austen"],
          answer: 0
        },
        
        {
          question: "What is the largest planet in our solar system?",
          choices: ["Mars", "Venus", "Saturn", "Jupiter"],
          answer: 3
        }
        
        
      ];
      
      for (var i = 0; i < questions.length; i++) {
        var question = questions[i].question;
        document.write(question);
        var options = questions[i].choices;
        for (var opt in options) {
           for (var radios in userChoices) {
             userChoices[radios].value = options[opt];
             
           }
        }
        
      }
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  
  <input type="radio" name="choices"><br>
  <input type="radio" name="choices"><br>
  <input type="radio" name="choices"><br>
  <input type="radio" name="choices"><br>
  
  </body>
</html>

Answer №1

To make your JavaScript code more concise, consider the following:

      var questions = 
      [
        {
          question: "Which city is the capital of France?",
          choices: ["Berlin", "Paris", "London", "Madrid"],
          answer: 1
        },
        
        {
          question: "What is the currency of Japan?",
          choices: ["Yen", "Won", "Dollar", "Euro"],
          answer: 0
        }
        
        
      ];
      
      for ( var i = 0; i < questions.length; i++ ) {
        var question = questions[i].question;
        document.write ( question );
        var options = questions[i].choices;
        document.body.appendChild(document.createElement("br"));
         var name = "radio"+i; 
        for ( var opt in options ) {
        
          var radioEle = document.createElement("input");
          radioEle.type = "radio";          
          radioEle.value = options[opt];
          radioEle.name = name;
          document.body.appendChild(radioEle);
          var label = document.createElement("Label");
          label.innerHTML = options[opt];
          document.body.appendChild(label);
          document.body.appendChild(document.createElement("br"));
        }
        
        document.body.appendChild(document.createElement("br"));
        
      }

Answer №2

If you require further clarification, I am happy to provide it.

<script>

    window.onload = function () {

        var questions =
      [
        {
            question: "What is the capital city of Japan?",
            choices: ["Osaka", "Kyoto", "Tokyo", "Hiroshima"],
            answer: 2
        },

        {
            question: "What is the capital of France?",
            choices: ["Berlin", "Paris", "Madrid", "Rome"],
            answer: 1
        }


      ];

        var container = document.getElementById('container');
        for (var i = 0; i < questions.length; i++) {
            var questionContainer = document.createElement('DIV');
            questionContainer.textContent = questions[i].question;

            var options = questions[i].choices;
            for (var opt in options) {
                //create radiobutton
                //append radiobutton to a div 
            }
            container.appendChild(questionContainer);
        }
    };
 </script>

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

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

What should I do if Max and Min are showing up as true instead of actual numbers?

I am trying to find the minimum and maximum numbers in an array, but I keep getting an error saying that the address of a function will always evaluate to true instead of a number. I'm not sure what changes need to be made. #include <iostream> ...

Why is there an issue with the way I am defining this Javascript variable?

In my JavaScript file, milktruck.js, I have defined an object called TruckModel. My goal is to create an array of TruckModel objects because in my multiplayer game, I cannot predict how many players will enter or exit at any given time. The issue I am fa ...

The addition of special characters to strings in TypeScript through JavaScript is not functioning as expected

I need assistance on conditionally appending a string based on values from captured DOM elements. When the value is empty, I want to include the special character "¬". However, when I try adding it, I get instead because the special character is not reco ...

Node.JS AJAX request with no data payload

Encountering an issue where no data is being received on the server side from an AJAX request because the req.body is empty (console logs it as {}). script.js: $("#button").click(function(){ var number = $("#number").val(); $.ajax({ ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

Pulling Tag-Specific XML Information into an Array using DOMDocument and foreach loop

In my quest to extract data from an XML document and organize it into an array, I am utilizing the DOMdocument along with foreach loops. The specific data I am interested in resides within the <description> tag. However, there's a twist - I only ...

Issues with Datepicker functionality in Bootstrap 5 are causing it to malfunction or not display

I am having trouble incorporating a timepicker on my webpage with bootstrap 5. The calendar feature isn't loading properly, preventing me from selecting any dates. I'm unsure if the issue lies with an error on my end or if the plugin isn't c ...

Activate a button upon the user clicking the Enter key

Is there a way to automatically trigger a button click when the user presses the Enter key inside an input field? I've attempted to achieve this functionality, but have been unsuccessful so far. Here is my code snippet: <!DOCTYPE htm ...

Activate inline javascript within LESS styling

I am interested in incorporating inline JavaScript into my less files, but I received the following notification: Inline JavaScript is not enabled. Have you configured it in your settings? What steps can I take to enable this feature? ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

React- Input value disappears after submission

Implementing validation for email-based input has been a bit of a challenge for me. I have managed to set up the debounce function for onChange event handling, but encountered a strange issue. The problem arises when the user submits an invalid string bef ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Unable to import CSV file

I'm currently in the process of developing a CSV editor that involves importing a CSV file and converting it into HTML tables. Below is the code I have been working on: <html> <head> <title></title> </head> <body& ...

Implementing Role-Based Access Control (RBAC) with an express backend and passport authentication

I am currently in search of an RBAC package or a demonstration using middleware on Express router. My goal is to establish different roles such as admin, manager, and user during registration, and then verify these roles with each backend request. Althou ...

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...

Show a component when there is no input value, then conceal it when an input value is present

Recently, I attempted to position a paragraph absolutely in relation to an input element. My goal is to conceal the paragraph when the input has a value, and reveal it when the input is empty. Here is the code snippet I created, however, it doesn't ...

Tips for resolving the <!--bindings={ "ng-reflect-ng-for-of": "" }--> bug

Just starting out with Angular and I am having some issues with event binding and property binding in my game-control component. I have a button that, when clicked, adds numbers to an array using setInterval method. I am also passing data between compone ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

How can I add information into a nested div element?

I encountered an issue when attempting to insert data into my block. The div structure is as follows: <div class="1"> <div class="2"> <div class="3"> <div class="4"></div> </div> ...