Reputation: 673
I have a generated table that looks fine except for the table headings are not lined up with the data, any help would be appreciated.
The code gets JSON and then loops through it while building a table to display it finally inside a div on the HTML page.
The code is below:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
* {
margin: 0;
}
html,
body {
background-color: white;
font-family: arial, helvetica, verdana, sans-serif;
font-size: 16pt;
}
.d0 {
background-color: #EFFBFB; /*#FCF6CF;*/
}
.d1 {
background-color: #E0F8F7; /*#FEFEF2;*/
}
</style>
</head>
<body>
<div id="des"></div>
</body>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
(function($) {
var json = {
1: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
2: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
3: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
4: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
5: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
6: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
7: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
8: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
9: { description:"Description", code:"1234", code1:"1234", code2:"1224"},
10: { description:"Description", code:"1234", code1:"1234",
code2:"1224"}
};
var tableHeader =
"<table>" +
"<tr>" +
"<th>Actions</th>" +
"<th>Description</th>" +
"<th>Code</th>" +
"<th>Code1</th>" +
"<th>Code2</th>" +
"</tr>";
var tableFooter = "</table>";
console.log(tableHeader);
$("#des").append(tableHeader);
$.each(json, function(key, value) {
var cssName = "d";
var cssKey = key % 2 == 0 ? 1 : 0;
cssKey = cssName + cssKey;
var html =
"<tr class=\"" + cssKey + "\">" +
"<td><a href=\"/common/Service?id=" + key + "\">Modify</a></td>" +
"<td>" + this.description + "</td>" +
"<td>" + this.code + "</td>" +
"<td>" + this.code1 + "</td>" +
"<td>" + this.code2 + "</td>" +
"</tr>";
console.log(html);
$("#des").append(html);
});
$("#des").append(tableFooter);
console.log(tableFooter);
})(jQuery);
Upvotes: 3
Views: 142
Reputation: 92933
jQuery will automatically close any HTML elements you create. You can't append the <table>
tag separately from the </table>
tag.
So instead of
$("#des").append(tableHeader);
// ....
$("#des").append(html);
// ....
$("#des").append(tableFooter);
You should append the empty table first, then append rows to the table body:
$("#des").append(tableHeader + tableFooter);
// ...
$("#des tbody").append(html);
Even better, combine everything into a single string, and append that all at once for a performance boost:
var table_html = tableHeader;
// ....
table_html += html;
// ....
table_html += tableFooter;
$("#des").append(table_html);
Upvotes: 4