Ryan Ellis
Ryan Ellis

Reputation: 21

Nested 'for' Loop to Create Table

I have been working through a course called "The Odin Project", and I have hit a wall on a project were we have to create an Etch-A-Sketch like sketchpad.

The gist of the project is... Whenever you mouse over a cell in the table, a class is added to that cell that changes the color. I have created some code using jQuery/javascript to create a square grid by appending table rows and cells using two 'for' loops (see script below).

My issue is whenever I run the 'for' loops with the append code to create the grid I do not get a square grid. For example, I would think setting up both of the 'for' loops to a limit of 4 should give me a grid with 4 rows with 4 cells a piece. What I am actually getting is the first row has 16 cells, second row has 12 cells, etc... Where am I going wrong here?

Link to jsfiddle...

http://jsfiddle.net/rellbows/qka0ago7/1/

for (var w = 0; w < 4; w++) {
  $('tbody').append('<tr></tr>');
  for (var j = 0; j < 4; j++) {
    $('tr').append('<td class="square"></td>');
  }
}

Upvotes: 1

Views: 1915

Answers (3)

PeteB
PeteB

Reputation: 372

Try this: fiddle

$(document).ready(function() {

    for (var w = 0; w < 4; w++) {
            $('tbody').append('<tr>');
                for(var j = 0; j < 4; j++) {
                    $('tbody').append('<td class="square"></td>');
                }
            $('tbody').append('</tr>');
        }

})

Two changes... first you must always append onto the same element 'tbody'. Using $(tr) was appending onto ALL of the <tr> tags.
Second the start and end td tags need to be on each side of the inner loop.

Upvotes: 0

Steve
Steve

Reputation: 9571

You are appending the each table cell to every tr tag that has come before.

Instead, you should identify each row and append the current row's cells to that row.

for (var w = 0; w < 4; w++) {
    $('tbody').append('<tr id="row' + w + '"></tr>');
    for(var j = 0; j < 4; j++) {
        $('#row' + w).append('<td class="square"></td>');
    }
}

JSFiddle

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240928

You need to append the square td elements to the last tr element you just created. You were appending the td elements to all the tr elements.

You can either use the :last selector, or the .last() method for this.

Updated Example

$('tr:last').append('<td class="square"></td>');

You could also just create a tr element, append the td elements to it, and then append that tr element to the table:

Updated Example

for (var w = 0; w < 4; w++) {
    var $tr = $('<tr></tr>');
    for (var j = 0; j < 4; j++) {
        $tr.append('<td class="square"></td>');
    }
    $('tbody').append($tr);
}

Upvotes: 4

Related Questions