Cameron
Cameron

Reputation: 28793

Pulling parts of JSON out to display them in a list

I have the following JSON:

var questions = {
    section: {
        "1": question: {
            "1": {
                "id" : "1a",
                "title": "This is question1a"
            },
            "2": {
                "id" : "1b",
                "title": "This is question2a"
            }
        },
        "2": question: {
            "1": {
                "id" : "2a",
                "title": "This is question1a"
            },
            "2": {
                "id" : "2b",
                "title": "This is question2a"
            }
        }
    }
};

NOTE: JSON changed based on the answers below to support the question better as the original JSON was badly formatted and how it works with the for loop below.

The full JSON will have 8 sections and each section will contain 15 questions.

The idea is that the JS code will read what section to pull out and then one by one pull out the questions from the list. On first load it will pull out the first question and then when the user clicks on of the buttons either option A or B it will then load in the next question until all questions have been pulled and then do a callback.

When the button in the appended list item is clicked it will then add it to the list below called responses with the answer the user gave as a span tag.

This is what I have so far:

    function loadQuestion( $section ) {

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

    for (var i = 0; i < data.length; i++) {

        var item = data[i];

        if (item === $section) {
            $('#questions').append('<li id="' + item.section.questions.question.id + '">' + item.section.questions.question.title + ' <button class="btn" data-response="a">A</button><button class="btn" data-response="b">B</button></li>');
        }
    }
});

}

    function addResponse( $id, $title, $response ) {

        $('#responses').append('<li id="'+$id+'">'+$title+' <span>'+$response+'</span></li>');

    }

    $(document).ready(function() {

        // should load the first question from the passed section
        loadQuestion( $('.section').data('section') );

        // add the response to the list and then load in the next question
        $('button.btn').live('click', function() {

            $id = $(this).parents('li').attr('id');
            $title = $(this).parents('li').html();
            $response = $(this).data('response');

            addResponse( $id, $title, $response );

            loadQuestion ( $('.section').data('section') );

        });

    });

and the HTML for the page (each page is separate HTML page):

<div class="section" data-section="1">

            <ul id="questions"></ul>

            <ul id="responses"></ul>

        </div>

I've become stuck and confused by how to get only the first question from a section and then load in each question consecutively for that section until all have been called and then do a callback to show the section has been completed.

Thanks

Upvotes: 0

Views: 296

Answers (2)

sajawikio
sajawikio

Reputation: 1514

  1. Do not have multiple id's in html called "section."
  2. Do not have multiple keys in your JSON on the same level called "section". Keys in JSON on the same level should be unique just as if you are thinking about a key-value hash system. Then you'll actually be able to find the keys. Duplicate JSON keys on the same level is not valid.

One solution can be section1, section2, etc. instead of just section. Don't rely on data-section attribute in your HTML - it's still not good if you have "section" as the duplicate html id's and as duplicate JSON keys.

If you have only one section id in HTML DOM, then in your JSON you must also have just one thing called "section" e.g.:

var whatever = {
                    "section" : { 
                               "1":  {
                                        "question" : {
                                                       "1" : {
                                                          "id" : "1a",
                                                          "title" : "question1a"
                                                              },
                                                       "2" : {
                                                          "id" : "2a",
                                                          "title"  : "question2a"
                                                              }
                                                     }
                                      },                                 
                                "2":  {
                                        "question" : {
                                                       "1" : {
                                                          "id" : "1a",
                                                          "title" : "aquestion1a"
                                                              },
                                                       "2" : {
                                                          "id" : "2a",
                                                          "title"  : "aquestion2a"
                                                              }
                                                     }
                                      }
                                 }
               }
console.log(whatever.section[1].question[1].title); //"question1a"

To get question, do something like this:

   function loadQuestions(mySectionNum) {

       $.getJSON('whatever.json', function(data){

        var layeriwant = data.section[mySectionNum].question;

           $.each(layeriwant, function(question, qMeta) {
               var desired = '<div id="question-' + 
                              qMeta.id +
                              '"' + 
                              '>' + 
                              '</div>';
               $("#section").append(desired);
               var quest = $("#question-" + qMeta.id);
               quest.append('<div class="title">' + qMeta.title + '</div>');
               //and so on for question content, answer choices, etc.
           });



       });
   }

then something like this to actually get the questions:

    function newQuestion(){
       var myHTMLSecNum = $("#section").attr('data-section');
       loadQuestions(myHTMLSecNum);
    }

    newQuestion();

  //below is an example, to remove and then append new question:

    $('#whatevernextbutton').on('click',function(){
       var tmp = parseInt($("#section").attr('data-section'));
       tmp++;
       $("#section").attr('data-section', tmp);
       $("#section").find('*').remove();
       newQuestion();
    });

Upvotes: 2

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

Technically your getJSON function always retrieves the same data. Your code never compares the id given to the id you're extracting.

Your getJSON should look something like:

function loadQuestion( $section ) {
        for (var i = 0; i < questions.section.length; i++) {

            var item = questions.section[i];
            if (item.id === $section) {
                for (var j = 0; j < item.questions.length; j++) {
                    $('#questions').append('<li id="' + 
                        item.questions[i].id + '">' + 
                        item.questions[i].title + 
                        ' <button class="btn" data-response="a">A</button><button class="btn" data-response="b">B</button></li>'
                    );
                }
           }
        }
}

Modify your JSON to:

var questions = {
    section: [{
        id: 1,
        questions: [{
            id: "1a",
            title: "This is question1a"
            },{
            id: "2a",
            title: "This is question2a"
        }]},{
        id: 2,
        questions: [{
            id: "1a",
            title: "This is question1a"
            },{
            id: "2a"
            title: "This is question2a"
        }]
    }]
};

Edit: your first parameter of getJSON is the URL of the JSON returning service.

You don't need getJSON at all if your JSON is already defined on the client. I have modified the code above.

Upvotes: 1

Related Questions