S.P.
S.P.

Reputation: 369

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'))

Upvotes: 0

Views: 292

Answers (2)

davidkonrad
davidkonrad

Reputation: 85528

You are only inserting the last <tr>, insertAfter() should be called in each loop. However, when you are using jQuery, I think you actually should use jQuery - building up plain HTML in strings is a bad idea :

var array = ["Laura","Michael","Steve"], $td, $tr;
array.forEach(function(value) {
  $tr = $('<tr>').insertAfter($('#rowTitle')), $td = $('<td>').appendTo($tr)
  $td.text(value)
})

Produces valid markup with rows in same order as array. And as a side-effect, more readable and more maintainable than creating complex '<tr>' + '<td>' etc strings.

Upvotes: 1

Dhara Parmar
Dhara Parmar

Reputation: 8101

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

Upvotes: 1

Related Questions