panchita911 panchita911 - 11 days ago 10
Javascript Question

Why is my json array not outputing input type radio for each line

I don't know why the radio is only outputing the whole line choices and not each of them. I am trying to do a quiz/result code

HTML FILE

<html><br>
<head><br>
<meta charset="UTF-8"><br>
<title>Coffee Addict Quiz</title><br>
<link href="css/main.css" rel="stylesheet" type="text/css"><br>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script><br>
</head>

<body>

<div id="container"><br>
<h1> How much of a coffee addict are you?</h1>

<div class="questionCon"></div><br>
<div class="questionCon"></div><br>
<div class="questionCon"></div><br>
<div class="questionCon"></div> <br>

</div><br>
<script src="js/questions.json"></script><br>
<script src="js/xml.js"></script>

</body><br>
</html>


JSON file

[{
"question": "What does your morning look like?",
"choices": ["Go for run", "Make coffee", "Cant talk running late!!"]
}, {
"question": "How many cups of coffee you drink in a day?",
"choices": ["None", "1-3", "4-7"]
}, {
"question": "Which sounds the best right now?",
"choices": ["Cappuccino", "Latte", "Espresso"]
}, {
"question": "Do you drink coffee to pull all nighters?",
"choices": ["No, I like my sleep", "Sometimes", "Yes"]
}]


JS FILE

(function() {
"use strict";
var questionCons = document.querySelectorAll(".questionCon");
console.log(questionCons)

function loadquestions() {
$.getJSON("js/questions.json")
.done(function(questions) {
console.log(questions);
for (var i = 0; i < questions.length; i++) {
questionCons[i].innerHTML += //plus and equal so it doesnt overright everyvalue.
"<p>" + questions[i].question + "</p>" + '<input type="radio" >' + questions[i].choices;

}
})

.fail(function() {
alert("your browser is outdated");

A.J A.J
Answer

It works! Need to add name attribute in input tag

Example Snippet:

var test = [{
  "question": "What does your morning look like?",
  "choices": ["Go for run", "Make coffee", "Cant talk running late!!"]
}, {
  "question": "How many cups of coffee you drink in a day?",
  "choices": ["None", "1-3", "4-7"]
}, {
  "question": "Which sounds the best right now?",
  "choices": ["Cappuccino", "Latte", "Espresso"]
}, {
  "question": "Do you drink coffee to pull all nighters?",
  "choices": ["No, I like my sleep", "Sometimes", "Yes"]
}]

var questionCons = document.querySelectorAll(".questionCon");

for (var i = 0; i < test.length; i++) {
  questionCons[i].innerHTML += "<p>" + test[i].question + "</p>";
  $.each(test[i].choices, function(index, value) {
    questionCons[i].innerHTML += '<input type="radio" name=quistion"' + i + '" >' + value;
  })

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="questionCon"></div>
<div class="questionCon"></div>
<div class="questionCon"></div>
<div class="questionCon"></div>

Comments