Radio buttons associated with array keys

I am trying to implement radio buttons for each key in a random array. I want the radio buttons to appear only for the keys in the allQuestions[index].answers array, which has 3 index keys.

So far, I have been unable to achieve this with my current code.

const allQuestions = [{
    question: "Which of them is from compton",
    answers: ["Nas", "Tupac", "Omarion", "Kendick"],
    correctAnswer: "Kendrick"
  },
  {
    question: "founder of HipHop",
    answers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
    correctAnswer: "Bambata"
  },
  {
    question: "Who won BET Hip Hop Album 2018",
    answers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
    correctAnswer: "Kendrick",
  },
  {
    question: "Best Female HipHop Art 2018",
    answers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
    correctAnswer: "Nicki"
  }
]

function render() {
  var index, unique;
  var print = '<ul>';
  for (i = 0; i < allQuestions.length; i++) {
    index = Math.floor(Math.random() * allQuestions.length);
  }

  var showQuiz = document.getElementById('showQuiz');
  var showAnswers = document.getElementById('showAnswers');

  showQuiz.style.color = 'red';
  showQuiz.innerHTML = allQuestions[index].question;
  showAnswers.innerHTML = allQuestions[index].answers;

  // Trying to use the unshift method here but it's not functioning correctly
  showAnswers.unshift('<input type="radio" value="allQuestions.answers[]');

}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>

Answer №1

It seems like there is an attempt to utilize the Array method unshift() on a DOM element. It appears that the intention is to create a list of radio buttons for each answer within the allQuestions.answers[] array. This can be achieved using a for loop or a map function as shown below:

An improvement could be made by including answersAsHtml and utilizing join(" ") to enhance readability, thereby joining each array element with a space instead of a comma.

const allQuestions = [{
    question: "Which of them is from compton",
    answers: ["Nas", "Tupac", "Omarion", "Kendick"],
    correctAnswer: "Kendrick"
  },
  {
    question: "founder of HipHop",
    answers: ["Tupac", "Eazy E", "Kendick", "Bambata"],
    correctAnswer: "Bambata"
  },
  {
    question: "Who won BET Hip Hop Album 2018",
    answers: ["Kendrick", "Bruno", "Jay Z", "Drake"],
    correctAnswer: "Kendrick",
  },
  {
    question: "Best Female HipHop Art 2018",
    answers: ["Azelia", "Nicki", "Cardi_b", "Mama Rap"],
    correctAnswer: "Nicki"
  }
]

function render() {
  var index, unique;
  var print = '<ul>';
  for (i = 0; i < allQuestions.length; i++) {
    index = Math.floor(Math.random() * allQuestions.length);
  }

  var showQuiz = document.getElementById('showQuiz');
  var showAnswers = document.getElementById('showAnswers');
  var answersAsHtml = allQuestions[index].answers.map(ans => `<input type="radio" value="${ans}">${ans}</input>`).join(" ");

  showQuiz.style.color = 'red';
  showQuiz.innerHTML = allQuestions[index].question;
  showAnswers.innerHTML = answersAsHtml;

}
<div id="question" style="text-align: center"> Quiz</div>
<button type="button" onclick="render()">Next Quiz</button>
<div id="showQuiz"></div>
<div id="showAnswers"></div>

Answer №2

Attempting to input content into an html element, which is not an array. It seems you may be after a solution along these lines.

populateAnswers.innerHTML = allQuestions[index].options.map(function (option){
        return '<input type="radio" name="answers" value="' + option + '"/>' + option
})

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

What is the best way to incorporate a Thymeleaf message stored in message.properties into my JavaScript file?

Is there a way to insert messages from a message.properties file into a javascript file similar to how it's done in an HTML file? For example, on my home page I have a title listed as: <h1 th:text="#{home.screen.title}"></h1> Where home ...

Creating Dynamic Buttons in Laravel with AJAX and jQuery

Hello, I need help creating dynamic buttons as I am not familiar with ajax or jquery. I currently have a dynamic button running, but I want to create another dynamic button after I add another form. Here is my code. Please take a look at my image, as I am ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...

Creating a character jump animation on an HTML5 canvas

While following a tutorial on creating character animations, I encountered an issue. The tutorial, located at , made it easy to make the character move left (the right movement was already implemented). However, I am struggling with how to animate the char ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Saving a collection of unique identifiers in Firebase

Struggling to find a solution for organizing Firebase data: Each user has posts with generated IDs, but how do I store these IDs in a user node efficiently? Currently using string concatenation and treating them like a CSV file in my JS app, but that feel ...

The redirection to the specified URL is not working as expected in Ajax

I'm currently struggling to figure out why my AJAX code is not working as expected, specifically with redirecting to the provided URL. I've attempted troubleshooting by adding an alert message within my PHP code to confirm if it's redirectin ...

Using Golang to assign the output of a function to elements within a Struct array

I need help making the Struct array return values from a Function I have defined later in my code. I have created a struct named "array" with an info array containing all values. Each element in the info array needs to correspond to specific values: in ...

Adjusting the width of a product slider based on window size changes using CSS media queries

Currently, I have a functional product slider that I am attempting to adjust the width for smaller viewports, but it is proving to be a challenge. Upon loading the document, the code tallies the width of each product item and initiates slides when buttons ...

What steps can be taken to prevent the Google search bar from adjusting focus in a Chrome extension?

Currently, I am in the process of developing a Chrome extension that incorporates some of the key functions from the vimperator plugin on Firefox. One issue I am facing is capturing keystrokes before a webpage does. An example of this difficulty can be se ...

How can I prevent ajax loader from overlapping headers in jquery-datatables?

Currently, I am developing a web application that utilizes jQuery data tables to load data from the server side. One issue I have encountered is that when the data table first loads, the loader covers the headers, creating a visibility problem as depicted ...

Error message: "The contract is not defined in thirdweb-dev/react

I am currently using thirdweb-dev/react library to interact with a smart contract. However, I am encountering an issue where the contract is showing up as undefined in my code along with the following error message: query.ts:444 Error: Could not ...

How a JavaScript Alert is disrupting the design of my ASP.NET Web Application

Despite finding a similar question, the provided answer did not resolve my issue. This is how my application typically appears: However, after triggering a JavaScript alert, the width of menu items becomes distorted and an additional part is added to the ...

Is there a way to enable Fancybox to change to the adjacent gallery by simply using the 'up' or 'down' arrow keys?

I am currently working on a layout that consists of a vertical column of thumbnail images, each linked to its own gallery with additional images. When the user clicks on a thumbnail image, Fancybox opens, allowing them to navigate through the images within ...

Creating an error handler in PHP for dynamically adding or removing input fields is a crucial step in ensuring smooth and

I designed a form with multiple fields, including a basic input text field and dynamic add/remove input fields. I successfully set the first field as required using PHP arguments, but I'm struggling to do the same for the additional fields. I need as ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

Incorporating Next and Previous navigation buttons to my slideshow

I'm looking to enhance my image slider by including next and previous buttons, but I'm unsure of how to proceed. Can anyone provide guidance or assistance with this? Below is the basic structure that I currently have in place: Here is the code s ...

Select value not updating as expected

I have a select box that is linked to a switch statement in PHP, which changes the order of the results returned from the database based on the value selected in the select box. However, I am facing an issue with my JavaScript not working correctly. Can an ...

Creating a slider with an input box using React hooks

Interactive Slider and Input Number Field const _defaultData = [ { percent: 0 }] const [data,setData] = useState(_defaultData) <input type="range" min="0" max="100" defaultValue={data.percent} classNa ...