5

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>"}
];
Ram
145k16 gold badges174 silver badges201 bronze badges
asked Apr 28, 2015 at 0:25
4
  • 10
    Yes, by using arrays! ... answers: ["Yes", "No"] 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 accomplish? Commented Apr 28, 2015 at 0:30
  • @EternalHour The code has a syntax error. So it's not working. Commented Apr 28, 2015 at 0:34
  • 2
    Note that your question has nothing to do with jQuery. You have defined a JavaScript array. Commented Apr 28, 2015 at 0:44

1 Answer 1

10

You 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"
suslov.nikita
44.7k11 gold badges92 silver badges113 bronze badges
answered Apr 28, 2015 at 1:03
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.