0

I have an object window.Think and an array:

window.Think.questions = [
  {answers: [
    {a: 1, b: 2}
  ]}
];

I'm trying to .append() part of this array into an element .buttons in my html.

How can I modify this so it prints part of my array?

$think = window.Think.new;

$(document).ready(function(){
    $(".buttons").append($think.questions[1]);
});
3
  • 1
    you'll have to either stringify the array, or iterate over it creating text/html. Commented Nov 26, 2013 at 23:04
  • 2
    what do you want to append and in what format? Commented Nov 26, 2013 at 23:11
  • I want to take 1 and put it as the name of a checkbox. <input type="checkbox" name="1"> Commented Nov 26, 2013 at 23:12

3 Answers 3

1

If you just want to append

A is: 1 -- B is: 2

with this exact data structure, you would do:

$(document).ready(function(){
    $think = window.Think.questions;
    $(".buttons").append("A is: " + $think[0].answers[0].a + " -- B is: " +$think[0].answers[0].b);
});

EDIT:

I just saw your comment above... here is what you would need to do:

$(document).ready(function(){
    $think = window.Think.questions;
    $(".buttons").append('<input type="checkbox" name="' + $think[0].answers[0].a + '"/>');
    $(".buttons").append('<input type="checkbox" name="' + $think[0].answers[0].b + '"/>');
});

You probably want the name to be something different than just an integer... are you sure you don't mean value?

Sign up to request clarification or add additional context in comments.

Comments

1

As @KevinB pointed out, you will have to stringify the portions that you want to display in the button, for instance:

var answers = window.Think.questions[0].answers[0],
    values = [answers.a, answers.b].join(' ');// turn the array values into a space delimited string

$('.buttons').append(values)

Comments

1

Assuming your checkbox has an ID:

$('#cheboxID').attr('name', $think[0].answers[0].a);

Comments

Your Answer

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.