5

i have the following code:

$.each(data.People, function (i, person) {
   html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
        });

I want to change this code so if the the array (data.People) has more than 20 people, it will do what its doing above for the first 20 people and then just show text saying "X" more people... so for example if the array had 100 people it would show the first 20 and then just say "80 more people . . ."

I am assuming i need some counter inside the each statement but wanted to see the best way to break out of that and show the remaining text.

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • do you want this "80 more people . . ." people clickable so that if the user click you show next 20 or you just want it as a text ??? – dku.rajkumar Dec 29 '11 at 18:41
  • possible duplicate of [How to Break out of Jquery's Each Loop](http://stackoverflow.com/questions/1784780/how-to-break-out-of-jquerys-each-loop) – outis Mar 28 '12 at 05:00

2 Answers2

14

return false breaks from each loop in jQuery, just like break in for loop in plain JavaScript. And return true is like continue.

For the X part you would need to get the length of the collection being iterated since each doesn't provide that info, unfortunately.

So, in your case:

$.each(data.People, function (i, person) {
   if (i == 20) {
     html.push("<p>" + (data.People.length - i) + " more people...</p>");
     return false;
   }
   html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
7

Your counter is i in your code. All you need to do is return false when i == 20 to terminate the each.

$.each(data.People, function (i, person) {
  if (i == 20) { return false; }
  html.push("<img title='" + person.Name + "' height='45' width='45' src='" + person.Picture + "' /> ");
});
mrtsherman
  • 39,342
  • 23
  • 87
  • 111