Reputation:
var text = "";
for (var x = 0; x < questions.length; x++)
{
text += (x+1) + ". " + questions[x] + "<br>";
}
document.getElementById("q").innerHTML = text;
I have an array of questions (size=5) and 5 arrays of answers for each questions.
var ans1 = ["answer","answer","answer","answer"];
var ans2 = ["answer","answer","answer","answer"];
var ans3 = ["answer","answer","answer","answer"];
var ans4 = ["answer","answer","answer","answer"];
var ans5 = ["answer","answer","answer","answer"];
var questions = ["q1", "q2", "q3", "q4", "q5"];
With my code, I'm just displaying the 5 questions. I can't figure out how to insert a radio button group of answers for each questions. Help?
(I already did it on java but I can't convert it into javascript. I'm new to it :| ) Thanks in advance
Upvotes: 1
Views: 106
Reputation: 2117
We could keep answers in a two dimensional array. That way we could avoid using eval method. The first loop is on questions and the second loop is on answers. You can try the following approach:
var ans1 = ["answer","answer","answer","answer"];
var ans2 = ["answer","answer","answer","answer"];
var ans3 = ["answer","answer","answer","answer"];
var ans4 = ["answer","answer","answer","answer"];
var ans5 = ["answer","answer","answer","answer"];
var questions = ["q1", "q2", "q3", "q4", "q5"];
for (var x = 0; x < questions.length; x++)
{
var number = x + 1;
newp = document.createElement("p");
newp.appendChild(document.createTextNode((number) + ". " + questions[x]));
newp.appendChild(document.createElement('br'));
var thisAnswers = eval('ans' + number);
for(i in thisAnswers){
var ans = thisAnswers[i];
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = 'answer' + number;
radio.value = ans;
label.appendChild(radio);
label.appendChild(document.createTextNode(ans));
newp.appendChild(label);
}
document.getElementById("q").appendChild(newp);
}
Upvotes: 1
Reputation: 1
You can create radio options by creating an 'input' element through the DOM
var input = document.createElement("input");
You can make a radio type input by setting the type attribute
input.type = "radio";
You can also set the value of your input
input.value = ans1[0];
Here's a fiddle for a closer look: https://jsfiddle.net/0gw1ar21/2/
Upvotes: 0