2

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!

6
  • Can you please create JSFIDDLE of your code? jsfiddle.net Commented Dec 12, 2014 at 3:45
  • how would that help anything? Commented Dec 12, 2014 at 3:49
  • So that I/we/anyone will get your current code and I/we/anyone will try to solve your purpose/error/problem and that's how it works here or that's the best practice or that's the standard procedure/practice. Commented Dec 12, 2014 at 3:52
  • Ok, I'll work on getting it up there. Commented Dec 12, 2014 at 4:06
  • dont't need parseHtml() to create elements with jQuery, $('<table>') is fine Commented Dec 12, 2014 at 4:07

3 Answers 3

1

would this work for you:

edit

removed cruft-y code.

CODEPEN

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');
Sign up to request clarification or add additional context in comments.

6 Comments

I'm not familiar with slice(), but I can try this out and let you know if it works. Thanks!
Not yet. I tried out this code and it kept crashing on the forEach. It seems like it's infinite looping or something. I also tried modifying it a bit, to no avail. I see what you're trying to do there, though and will play around with it a bit.
Sorry for the multiple comments, but I just figured out that it's looping through the values fine but then dying after the last one. There are 21 total elements. After it deals with the last one, it doesn't seem to know what to do and hangs.
shouldn't be... no errors in dev tools on my end. try slightly updated ver
Yes. I guess the modified one is. I'll give you the nod for it. :)
|
0

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

1 Comment

Yea, I see this now, after I figured it out. Similar idea to what I got. Thanks!
0

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);
}                               

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.