Clemen Canaria Clemen Canaria - 6 months ago 30
HTML Question

Javascript: Split one table row into multiples of 5s column

Say I have an array with 11 elements

var sizeArr = ['abc','bcd','cde','def','efg','fgh','ghi','hij'.'ijk','klm','lmn'];


I wanted to create an HTML table based on the array above but wanted to divide the row into 5 columns. I have some code that looks similar to this:

var cntr = 1;
for (....) {
if (cntr == 1 || cntr % 6 == 0) {
html += "<tr>";
}

html +="<td>.....</td>";

if (cntr == sizeArr.length|| cntr % 5 == 0) {
html += "</tr>";
}
}


This code works ok for the first 10 elements. The output will be similar to his:

<tr>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>10 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>12</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>10.5 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>6</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>11 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>6</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>11.5 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>12</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>12 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>4</p>
</td>
</tr>
<tr>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>13 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>4</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>14 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>6</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>8 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>8</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>8.5 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>8</p>
</td>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>9 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>6</p>
</td>
</tr>
<td>
<p class='COLUMN-DATA-PADDING-TXT'>9.5 D(M) US</p>
<p class='COLUMN-DATA-PADDING-TXT'>6</p>
</td>


Notice the last td doesn't have the enclosing tr on it.

Thanks in advance.

Answer

You don't show what condition you are using in your for loop, so it's not really possible to be sure what is going wrong with your code. I would guess that it's not a good sign that the second if condition is testing cntr == sizeArr.length, because if the loop counter is equal to the array's .length that means that the "current" element at sizeArr[cntr] is undefined - the last element in the array is at position length-1.

Anyway, as far as implementing your requirement, what I'd suggest is making it a bit simpler by adding the first <tr> and final </tr> tags outside the loop, because then you only need one if statement:

var sizeArr = ['abc','bcd','cde','def','efg','fgh','ghi','hij','ijk','klm','lmn'];

var html = "";
var cols = 5;
for (var i = 0; i < sizeArr.length; i++) {
  if (i % cols === 0 && i > 0) {
    html += "</tr><tr>";
  }
  html += "<td>" + sizeArr[i] + "</td>";
}
html = "<tr>" + html + "</tr>";
// do something with the html, e.g., for demo purposes:
console.log(html);
document.body.innerHTML = "<table>" + html + "</table>";

Comments