I am trying to build a set of questions and answers for a questionnaire. Each instance has an id, a css class, a question, and at least one answer. Is it possible to have multiple values when there is more than one answer?
var qa = [
{id: "0", css: "multiple", question: "Do you own a home?", answers: "Yes", "No"},
{id: "1", css: "input", question: "Who will live in your home?", answer: "<textarea rows='5' class='textarea'></textarea>"}
];
I am trying to build a set of questions and answers for a questionnaire. Each instance has an id, a css class, a question, and at least one answer. Is it possible to have multiple values when there is more than one answer?
var qa = [
{id: "0", css: "multiple", question: "Do you own a home?", answers: "Yes", "No"},
{id: "1", css: "input", question: "Who will live in your home?", answer: "<textarea rows='5' class='textarea'></textarea>"}
];
Share
Improve this question
edited Apr 28, 2015 at 0:43
Ram
145k16 gold badges172 silver badges200 bronze badges
asked Apr 28, 2015 at 0:25
Solona MeadSolona Mead
711 gold badge1 silver badge5 bronze badges
4
-
10
Yes, by using arrays!
... answers: ["Yes", "No"]
– Ram Commented Apr 28, 2015 at 0:26 - Is the code in your question working or is it an example of what you are trying to acplish? – EternalHour Commented Apr 28, 2015 at 0:30
- @EternalHour The code has a syntax error. So it's not working. – Ram Commented Apr 28, 2015 at 0:34
- 2 Note that your question has nothing to do with jQuery. You have defined a JavaScript array. – Ram Commented Apr 28, 2015 at 0:44
1 Answer
Reset to default 10You can do this by turning the answers in to an array:
var qa = [{
id: "0",
css: "multiple",
question: "Do you own a home?",
answers: ["Yes", "No"]
}];
And than access it like this:
qa[0].answers[0] // for "Yes"
qa[0].answers[1] // for "No"
or
qa[0]['answers'][0]// for "Yes"
qa[0]['answers'][1] // for "No"
Or instead of an array you also can use an object:
var qa = [{
id: "0",
css: "multiple",
question: "Do you own a home?",
answers: [yes: "Yes", no: "No"]
}];
And than access it like this:
qa[0].answers.yes // for "Yes"
qa[0].answers.no // for "No"
or
qa[0]['answers']['yes']// for "Yes"
qa[0]['answers']['no'] // for "No"