S.P. S.P. - 1 month ago 9
jQuery Question

Convert array into table

I'm writing a dynamic table, the data is reading from array, but I can't successfully create the table, did I make something wrong?

html part:

<tr id="rowTitle">
<td align="middle"><strong>Name</strong></td>
</tr>


jQuery part:

var name = ["Laura","Michael","Steve"]
var count = 0

for (var i = 0; i < name.length; i++) {
var row = '<tr>'
+ '<td>' + name[count] + '</td>'
count++
+ '</tr>'
}

$(row).insertAfter($('#rowTitle'))

Answer

Try this:

var name = ["Laura","Michael","Steve"]
var count = 0
var row = ''; // initialize row outside loop 
for (var i = 0; i < name.length; i++) {
  row += '<tr>'+ '<td>' + name[count] + '</td>'+(count++)+'</tr>'; // append html string into row using +=
}
$(row).insertAfter($('#rowTitle')); // insert html after #rowTitle