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>