Reputation: 196539
On the callback of an ajax call i get an array of people objects with URL to their pictures. I have the following code:
html.push("<table class='tooltipProject'>");
html.push("<tr><td>");
$.each(data.People, function (index, person) {
html.push("<img width='44' src='" + person.PicLink + "' />");
});
html.push("</td></tr>");
html.push("</table>");
return html.join("");
I am taking this html and having it show up in a popup window. This works great because each of the arrays (data.People
) were small. I now have situation where they are large so the UI looks too wide. I can constrain my UI popup to be fixed width (lets say 500px) but I now need to generate a table where I don't ever want more than 5 images in a row and after that it should just to the next row
So I have 3 items in data.People
then it will show one row.
If I have 10 items in data.People
then I want to show 5 on row one and 5 on row 2.
I could created a TD for each picture but I am not sure that makes a difference as i still need the right logic to know when its time for a new row.
Upvotes: 0
Views: 98
Reputation: 627
One simple solution would be to just use index and an if
statement to your code. The result would look something like this:
html.push("<table class='tooltipProject'>");
html.push("<tr><td>");
$.each(data.People, function (index, person) {
html.push("<img width='44' src='" + person.PicLink + "' />");
if ((index+1) % 5 == 0) {
html.push("</td></tr><tr>");
}
});
html.push("</td></tr>");
html.push("</table>");
return html.join("");
Upvotes: 0
Reputation: 1967
If index is numeric you can use the modulo.
$.each(data.People, function (index, person) {
html.push("<img width='44' src='" + person.PicLink + "' />");
if ( ((index + 1) % 5) == 0) {
html.push("</td></tr><tr><td>");
}
});
index + 1
because your first element have index = 0.
Upvotes: 0
Reputation: 571
Use:
$.each(data.People, function (index, person) {
html.push("<img width='44' src='" + person.PicLink + "' />");
if((index+1)%5==0) html.push('</td></tr><tr><td>');
});
or if you decide to use div's (which is better), make that if
statement:
if((index+1)%5==0) html.push('</div><div>');
Upvotes: 0
Reputation: 92913
Just take the index of your $.each
loop, modulo 5, to determine when to start a row:
html.push("<table class='tooltipProject'><tr>");
$.each(data.People, function (index, person) {
html.push("<td><img width='44' src='" + person.PicLink + "'></td>");
if (index % 5 == 4 && index < data.People.length - 1) {
html.push("</tr><tr>");
}
});
html.push("</tr></table>");
return html.join("");
Upvotes: 2