hendrix hendrix - 5 months ago 20
jQuery Question

How to create a table in JS

I need to create a table in JS and show it in the page but it does not seem to work. I have two functions, the first one to actually create the table and the second one to order the elements in the table. I tried creating a simple div in html with id

showlist
but the table does not appear in the page. Please see the code below.

function myfunction() {
var array2 = [];
var list = "<table border ='1'>";
array2.sort(order);

list = list + "<tr>";
list = list + "<td colspan = '2'> TABLE </td>";
list = list + "</tr>";
list = list + "<tr>";
list = list + "<td> PRICE</td>";
list = list + "</tr>";

for (i = 0; i <= array2.length; i++) {
list = list + "<tr>";
list = list + "<td>" + array2[i].name + "</td>";
list = list + "<td>" + array2[i].price + "</td>";
list = list + "</tr>";
}
list = list + "</table>";
$("#showlist").html(list);
}

function order(n1, n2) {
if (n1.price > n2.price) {
return 1;
} else {
if (n1.price < n2.price) {
return -1;
} else {
return 0;
}
}
}

Answer

Your for loop <= runs from 0 to array2.length, it should be < - from 0 to array2.length-1.

for (i = 0; i < array2.length; i++) {
//            ^_ Notice change here
   ...
}

Else, the last iteration would throw undefined errors.

Uncaught TypeError: Cannot read property 'name' of undefined


Fiddle Example