I am populating data in jQuery into multiple html tables but everything after the second row keeps printing outside of the table.
I created a fiddle here to show what’s happening
https://jsfiddle.net/s81zb7ga/
I cannot work out why it keeps printing outside of the table.
My code with the loop is below:
var title = '';
$('#results_credentials').html("");
for(var i in data) {
var m = '';
var end_of_tbl = '</tbody>';
end_of_tbl += '</table>';
end_of_tbl += '</div>';
end_of_tbl += '</div>';
end_of_tbl += '</div>';
if(title !== data[i].title) {
if(title !== "") {
m += end_of_tbl;
}
title = data[i].title;
m += '<div class="panel-collapse box box-warning">';
m += '<div class="box-header">';
m += '<h3 class="box-title">';
m += '<a href="#box_expand_' + data[i].sequence + '" data-toggle="collapse" id="credential_title_' + data[i].sequence + '">' + data[i].title + '</a>';
m += '</h3>';
m += '</div><!-- /.box-header -->';
m += '<div class="box-body panel-collapse collapse2" id="box_expand_' + data[i].sequence + '">';
m += '<div class="table-responsive">';
m += '<table class="table table-bordered table-hover">';
m += '<thead>';
m += '<tr>';
m += '<th class="credential_group credential_group_' + data[i].title.replace(' ', '_') + '">Group</th>';
m += '<th>Note</th>';
m += '<th>Username</th>';
m += '<th>Password</th>';
m += '<th>Updated</th>';
m += '<th colspan="2">Actions</th>';
m += '</tr>';
m += '</thead>';
m += '<tbody>';
}
m += '<tr id="credential_row_' + data[i].sequence + '">';
m += '<td colspan="7">test</td>';
m += '</tr>';
$('#results_credentials').append(m);
}
2
Answers
As per epascarello's comment, it turns out the tags were automatically being closed by the browser.
So by moving
var m = '';
and$('#results_credentials').append(m);
outside of the for loop, it appends the whole table and data at once and therefore doesn't break the HTML.So there are other ways to generate dynamic content with jQuery. You can follow something as below: