Reputation: 2850
I have an html table with 3 columns and any number of rows (based on a database output.)
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The table shows the content properly but doesn't show the headers of each of the column such as Question
, Decision
, Whose Decision
What am I missing?
Upvotes: 0
Views: 1382
Reputation: 673
You replaced whole html. You need to apped html like
table.append(resultHtml);
Upvotes: 1
Reputation: 62536
By using table.html(...)
you override the entire content of your table (include the header).
You can use something like that:
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = $('<table>').append(table.find('tr').first()).html();
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Upvotes: 1
Reputation: 12025
You are overwriting the table in the javascript from what I can see. table.html(resultHtml) is replacing what you have in the html code.
Upvotes: 0