Reputation: 1393
I have an array with a (hypothetically) unknown number of elements. I say hypothetically since I can count them, but it could change and I don't want to have to keep editing code through the years based on that. I want the code to be able to handle any number of items.
I want to output these items in a table. So, I create the table:
var tbl = $.parseHTML('<table>');
Now, I want to make rows of 5 items each in this table. So I start, before the .each, by starting the first row:
var row = $.parseHTML('<tr>');
Then I start the loop:
$.each(myArray, function(index, value){
// Create cell
var cell = $.parseHTML('<td>');
(...fill the cell....)
// Insert the cell into the row
$(row).append(cell);
Here's where it gets tricky. I want to end the row and start a new row once I've created 5 cells...
if((index + 1) % 5 == 0){
$(tbl).append(row);
Right here, I need to start a new row. However, if I call it "row" again, it just adds to the currently existing row. If I try to reset it, it either deletes everything or crashes, depending on how I do it. How do I make it start a new row that will allow the looping above this to work for each subsequent row?
(The rest of the code...)
}
// Add final row if necessary
if(((index + 1) == $(myArray).length) && ((index + 1) % 5 != 0)){
$(tbl).append(row);
}
});
Hopefully, I've explained this well enough.
Thanks!
Upvotes: 2
Views: 5621
Reputation: 1393
GOT IT! (Thanks for the baseline, CODEPEN!)
var len = myArray.length / 5;
for (i=0; i<len; i++) {
var rowItems = myArray.slice(0,5);
var row = $.parseHTML('<tr>');
myArray = myArray.slice(5);
$.each(rowItems, function(index, item){
var cell = $.parseHTML('<td>');
$(cell).text(item);
$(row).append(cell);
});
$(tbl).append(row);
}
Upvotes: 0
Reputation: 4676
Todd's solution works great, so far as I can tell. Here's an alternative using a simple nested for
loop:
var tbl = $('<table>');
for (var i = 0; i < myArray.length / 5; i++)
{
var nextRow = $('<tr>');
$(tbl).append(nextRow);
var nextItem = 5 * i; // starts each row 5 elements more into the array
for (var j = 0; j < 5 && nextItem + j < myArray.length; j++) // stops when the array ends
{
var nextCell = $('<td>');
$(nextCell).html(myArray[nextItem + j]); // add the next array item
$(nextRow).append(nextCell);
}
}
$('div').append(tbl);
Here's a JSFiddle
Upvotes: 0
Reputation: 5454
would this work for you:
removed cruft-y code.
var items = ['asdf', 'qwer', 'rtyu', 'tyui', 'yuio', 'dfgh', 'zxcv', 'xcvb', '1234', 'isdfgt', 'foo'];
var $table = $('<table />').width('100%');
while (items.length) {
var rowItems = items.slice(0,5),
$tr = $('<tr>');
items = items.slice(5);
rowItems.forEach(function(item){
$('<td>', {
html: '<p><span>'+item+'</span></p>'
}).appendTo($tr.appendTo($table));
});
}
$table.appendTo('body');
Upvotes: 1