0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.