James James - 2 months ago 9
jQuery Question

Showing max of 10 available products

I know i can limit the loop but need to display a max of 10 if they are available...

$.each(data.results, function(index, item) {
console.log(item.available);
//console.log(data.results_count);
if(item.available == true) {
var link = $('<a></a>').attr('href', item.url);
link.append('<span class="thumbnail"><img src="' + item.thumbnail + '" /></span>');
link.append('<span class="title">' + item.title + '</span>');
link.wrap('<li></li>');
resultsList.append(link.parent());
}
});


Little new to JS so unsure how to do this, at the moment i only show if item is available but just want to display a maximum of 10 if thats possible.

Answer

Just keep a count of how many available ones you've already displayed, and don't allow it to go over 10. There's nothing JS-specific about this really, it's a general logical concept, but here's the JS implementation:

var AvailableItemCount = 0; //count of already displayed items

$.each(data.results, function(index, item) {
  console.log(item.available);
  //console.log(data.results_count);

  if(item.available == true && AvailableItemCount < 10) { //check that we haven't already displayed 10 items
    var link = $('<a></a>').attr('href', item.url);
    link.append('<span class="thumbnail"><img src="' + item.thumbnail + '" /></span>');
    link.append('<span class="title">' + item.title + '</span>');
    link.wrap('<li></li>');
    resultsList.append(link.parent());
    AvailableItemCount++; //increment the count of displayed available items
  }

  if (AvailableItemCount >= 10) { return false; } //don't waste time looping once we've displayed 10 items
});