user838437
user838437

Reputation: 1501

jQuery JSON nested loops

I have the following script:

function drawDimensions(divid) {
    $.getJSON('dimensions.json', function(data) {
        $.each(data, function(index) {
            var ppp = $('#' + divid).append("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
          $.each(this, function(k, v) {
              $('<div>').append(v).appendTo(ppp);
          });
        });
    });
}
drawDimensions('dim');

I'm trying to nest the divs so the values from the first loop will be the parents of the divs on the second loop.

What am I doing wrong? the second loop divs are not nested within the first one but simply appended after the first ones..

Upvotes: 1

Views: 290

Answers (2)

Meligy
Meligy

Reputation: 36594

The one obvious mistake (may not be the only) is that pppwill still refer to the parent div, not the one you created there.

use appendTo() as you do in inner loop, or have the assignment separate, like:

function drawDimensions(divid) {
    var $container = $('#' + divid);
    $.getJSON('dimensions.json', function(data) {
        $.each(data, function(index) {
          var ppp = $("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
          $container.append(ppp); // or ppp.appendTo($container);
          $.each(this, function(k, v) {
              $('<div>').append(v).appendTo(ppp);
          });
        });
    });
}
drawDimensions('dim');

Try and see how it goes, and tell me in comments.

Notes about sample code:

  • I cached getting the container div jQuery object, since there is only one anyway
  • Also, used $ as prefix to the variable I used. Just common practice with jQuery objects, not required.

Upvotes: 2

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

Your ppp is actually a reference to $('#' + divid), not to the newly created (outer) div.

Try this:

var ppp = $("<div class='dTitle'><img src='images/cleardot.gif' />" + index + "</div><br>");
ppp.appendTo('#' + divid);

Upvotes: 1

Related Questions