Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to have an object loop through HTML

Hi guys I have the following code of object and want to pass it to my "setImg" div on HTML. Do you guys know how to go about doing so:

$(document).ready(function () {  

var questions = [
{question: "Who is Zach Morris?",
 choices: ['images/ACslater.jpg','images/CarltonBanks.jpeg','images/ZachMorris.jpg'],
 quesNum: 1,
 correctAns: 2},

 {question: "Who is Corey Matthews?",
 choices: ['images/CoryMatthews.jpeg','images/EdAlonzo.jpg','images/Shawnhunter.jpg'],
 quesNum: 2,
 correctAns: 1},

 ];

 var userAnswer = $('quiz-container').onclick().val()  //THis needs to be looked into
 var counter = 0;
 var score = 0;


//function to loop choices put in HTML set up Counter

for (var i = 0; i < questions.length; i++)
{
    //INSERT HTML
    function update_question(question) {
    // build out new html string dynamically in JS
    var html_string = '<p>' question.text + '</p><li>' + question.choices[0] + '</li>' //etc
    // insert the html inside of a div with class name 'question'
    $('.setImg').html(html_string);
    counter++;
    }

}

1 Answer

Hi Alcibiades,

At the moment, your for loop is repeatedly declaring the update_question() function, but not actually calling it. Ideally you would declare a function outside of a loop.

At any rate, maybe you could try something like this? I've just written it without update_question() for clarity in this example.

var html_string = '';
// loop through questions array
for (var i = 0; i < questions.length; i++) 
{
   // put current question into a variable for convenience.
   var currentQuestion = questions[i];
   // put the question string between paragraph tags
   html_string += '<p>' + currentQuestion.question + '</p>';
   // create an unordered list for the choices
   html_string += '<ul>';
   // loop through the choices array
   for (var j = 0; j < currentQuestion.choices.length; j++) {
      // put the image as a list item
      html_string += '<li><img src="' + currentQuestion.choices[j] + '"></li>';
   }
   html_string += '</ul>';
}
$('.setImg').html(html_string);

Hope that helps.

Cheers, Amanda.