user7779924
user7779924

Reputation:

If index is a multiple of 4 add one to counter - JQUERY

I have a simple loop that loops through JSON data and counts how many objects there are. For every 4th object I would like to add 1 to a counter so that it technically groups the objects by 4.

I can't seem to get it right, it keeps returning the same value each time. Maybe someone else might know.

If you check the console.log(); you can see that the postCount stays the same.

I have included a link to the JSON file if needed. You will just have to change the url for the Ajax call.

Please see code below -

CODE -

var imgTitle;
var imgLink;

$.ajax({
    type: 'GET'
    , url: 'http://www.capetownetc.com/api/get_category_posts/?slug=news'
    , data: {
        get_param: 'value'
    }
    , dataType: 'jsonp'
    , success: function(data) {
    
        $.each(data.posts, function(i){
            imgTitle = data.posts[i].title;
            imgLink = data.posts[i].thumbnail_images.medium.url;
            console.log(imgTitle);
            
            var postCount = 0;
            
            if((i + 1) % 4 === 0){
                postCount = postCount+= 1;
                console.log(postCount);
            }

        });
        
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

JSON Data File

Upvotes: 0

Views: 179

Answers (3)

StudioTime
StudioTime

Reputation: 23989

As per my comment:

Put var postCount = 0; before the $.each loop...having it inside was resetting it on every "each"

As also mentioned in the comments, you can replace

postCount = postCount+= 1;

with

postCount++;

Upvotes: 0

user7779924
user7779924

Reputation:

Thanks to Darren Sweeney -

put var postCount = 0; outside of the $.each loop

Upvotes: 0

Milan Chheda
Milan Chheda

Reputation: 8249

postCount is assigned as 0 everytime. You need to put this outside of loop:

var imgTitle;
var imgLink;

$.ajax({
  type: 'GET',
  url: 'https://www.capetownetc.com/api/get_category_posts/?slug=news',
  data: {
    get_param: 'value'
  },
  dataType: 'jsonp',
  success: function(data) {
    var postCount = 0;
    $.each(data.posts, function(i) {
      imgTitle = data.posts[i].title;
      imgLink = data.posts[i].thumbnail_images.medium.url;
      console.log(imgTitle);
      if ((i + 1) % 4 === 0) {
        postCount++;
        console.log(postCount);
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Upvotes: 1

Related Questions