Warve
Warve

Reputation: 511

Load in JSON data into html for loop

Got a JSON array of questions and answers that I want to add into HTML, I can load in the data fine, problem is showing the data into each respective section. Just can't quite get it right as it's only showing the last question and the last option in the array for each section.

JSON data is:

[
    {
        "question": "What kind of event are you looking for",
        "option": [
            "Incentive Trip",
            "Birthday Party",
            "Insipiring Holiday",
            "Memorable Experience",
            "Wedding",
            "Conference",
            "Exciting Concert",
            "Crazy Festival",
            "Product Launch",
            "Stag Do",
            "Hen Do",
            "Surprise for loved ones"
        ]
    },
    {
        "question": "What are you looking to achieve?",
        "option": [
            "Bond up with your Clients",
            "Reward the best performers",
            "Say thank you to your team"
        ]
    },
]

jQuery code is:

$.getJSON('questions.json', function(data) {
    $.each(data, function(index, element) {

        // Add the question
        $.each( $('section'), function() {
            $('h2').text(element.question);
        });

        $.each( $('section .balloons'), function() {
            for(var i = 0; i < $(element.option).length; i++) {
                $('.balloons').html('<p>'+ element.option[i] +'</p>');
                console.log(element.option[i]);
            };

        });


    });
});

HTML is:

<section class="play" id="eventType">
        <h2></h2>
        <div class="balloons"></div>
    </section>
    <!-- Achieve -->
    <section class="achieve" id="achieve">
        <h2></h2>
        <div class="balloons">
            <div class="balloon"></div>
        </div>
    </section>

Upvotes: 0

Views: 138

Answers (2)

Mahedi Sabuj
Mahedi Sabuj

Reputation: 2944

You can Try this

$.getJSON('questions.json', function(data) 
{
    $.each($("section"), function (index){
      var result = data[index];
      var $ballons = $(this).find(".balloons");
      $(this).find("h2").html(result.question);

      $.each(result.option, function(idx) {
          $ballons.append('<p>'+ result.option[idx] +'</p>');
      });        
  });
});

FIDDLE DEMO HERE

Upvotes: 2

Sarjerao Ghadage
Sarjerao Ghadage

Reputation: 1544

$.getJSON('questions.json', function(data) 
{
    $.each(data, function(index, element)
    {
       $('h2').text(index.question);
       $('.balloons').html(index.option);

    });

});

Upvotes: 0

Related Questions