Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  138] [ 1]  / answers: 1 / hits: 15440  / 11 Years ago, tue, september 17, 2013, 12:00:00

I have a products page that I want to show 3 items in each row and then if it has more, create a new row and show more. So 3 cols per row with unlimited rows. Below is the code that I have that contains my loop which I assume the code will need to go into.



$(data).find('products').each(function() {

itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();

items +='<div class=row-fluid>
<div class=span3>Col 1</div>
<div class=span3>Col 2</div>
<div class=span3>Col 3</div>
</div>';

count++;

});


Here is where I need to do it but I am a little stuck on how to approach this. If the count is dividable by 3 I assume it will then need to create a new row.



Thanks for any help or input you can provide.


More From » html

 Answers
7

First of all, no need to handle a count variable on your own, the .each() function already supplies an index element (as an optional argument).



With the modulus operator you can get the remainder from dividing the index by 3. Then you can tell when do you need to print the opening of the row and the ending of it.



$(data).find('products').each(function(index) {

itemName = $(this).find('itemName').text();
itemDesc = $(this).find('itemDesc').text();
itemID = $(this).find('id').text();

if ((index % 3) == 0) items += '<div class=row-fluid>';

items += '<div class=span3>Col 1</div>';

if ((index % 3) == 2) items += '</div>';
});

if (items.substr(-12) != '</div></div>') items += '</div>';

[#75655] Sunday, September 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;