Meules
Meules

Reputation: 1389

Looping through json results

I have some JSON results pulled from a server. What I want to do is to loop through the first 3 of them, create some HTML and after that the same thing for the next three.

What I have is:

$.getJSON(url, function(data){                               

           var sliderHTML = "";

           $.each(data.collection.products, function(index, product){  

             sliderHTML += '<div class="rsContent">';
             sliderHTML += '<a class="rsLink" href="'+product.url+'">'+product.title+'</a>';  
             sliderHTML += '<img class="rsImg" src="'+image+'" />';   
             sliderHTML += '</div>';


       });

So the each loop must create a DIV rsContent with three images and links. After that it must create a new DIV rsContent with 3 new images and links. And so on. It should look like this:

<div class="rsContent">
  <a class="rsLink" href="">product</a>  // product 1
  <img class="rsImg" src="" />

  <a class="rsLink" href="">product</a>  // product 2
  <img class="rsImg" src="" />

  <a class="rsLink" href="">product</a>  // product 3
  <img class="rsImg" src="" />
</div>

<div class="rsContent">
  <a class="rsLink" href="">product</a>  // product 1
  <img class="rsImg" src="" />

  <a class="rsLink" href="">product</a>  // product 2
  <img class="rsImg" src="" />

  <a class="rsLink" href="">product</a>  // product 3
  <img class="rsImg" src="" />
</div>

etc....

I'm pretty new and I can't get this to work. Any suggestions?

Upvotes: 0

Views: 56

Answers (1)

letiagoalves
letiagoalves

Reputation: 11302

You can do something like this:

$.getJSON(url, function (data) {

    var sliderHTML = "";
    var i = 1;
    $.each(data.collection.products, function (index, product) {

        if (i == 1) {
            sliderHTML += '<div class="rsContent">';
        }

        sliderHTML += '<a class="rsLink" href="' + product.url + '">' + product.title + '</a>';
        sliderHTML += '<img class="rsImg" src="' + image + '" />';

        if (i == 3) {
            sliderHTML += '</div>';
            i = 1;
        }
        i++;
    });
    if(i != 1) sliderHTML += '</div>';

});

If your last group does not have exacly 3 elements you must do if(i != 1) sliderHTML += '</div>'; after the loop (or other validation) to close the last DIV element.

Upvotes: 1

Related Questions