Reputation: 81
I've been working on this for a day or so and I'm a bit stuck so I'm hoping I can come out of this with a clearer idea of what's going on.
Essentially I'm creating a HTML table using a nested for loop. The goal is to have a table that spans 7 columns per row.
var tbl = document.createElement("table");
for (var i = 15; i < 36; i++) {
for (var j = 0; j < 7; j++) {
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.createTextNode(i);
row.appendChild(cell);
tbl.appendChild(row);
}
cell.appendChild(cellText);
}
$('#calendar').append(tbl);
Anticipated Result:
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
Actual Result:
15
16
17
18
19
20
21
22
23
...
35
Simplified the result for the sake of typing less but if anyone can please point me in the right direction, I'd love to know where I might going wrong with this. Thank you.
Upvotes: 1
Views: 4235
Reputation: 2795
You can try like this
var calendar = document.getElementById('calendar');
var table = document.createElement("table"); /*Create `table` element*/
var rows = 3;
var cols = 7;
var counter = 15;
for (var i = 1; i <= rows; i++) {
var tr = document.createElement("tr"); /*Create `tr` element*/
for (var j = 1; j <= cols; j++) {
var td = document.createElement("td"); /*Create `td` element*/
var cellText = document.createTextNode(counter); /*Create text for `td` element*/
++counter;
td.appendChild(cellText); /*Append text to `td` element*/
tr.appendChild(td); /*Append `td` to `tr` element*/
}
table.appendChild(tr); /*Append `tr` to `table` element*/
}
calendar.appendChild(table); /*Append `table` to your HTML `calender` DIV*/
<div id="calendar"></div>
Upvotes: 5
Reputation: 52
Here you are: https://jsfiddle.net/0jvq1q0y/6/
var tbl = document.createElement("table");
for (var i = 15; i < 36; i++) {
if((i-15)%7==0)
{
var row = document.createElement("tr");
tbl.appendChild(row);
}
var cell = document.createElement("td");
var cellText = document.createTextNode(i);
row.appendChild(cell);
cell.appendChild(cellText);
}
$('#calendar').append(tbl);
Upvotes: 1