Reputation: 567
My code is working fine but I can't print table that I made from JSON values. Any suggestions??
var resData = {"key1":"value","key2":"value"};
var table = $('<html/>').append('<thead><tr><th>Filter</th><th>Values</th></tr></thead>').appendTo('body'),
tbody = table.append('<tbody/>');
$.each(resData, function(key, value){
tbody.append('<tr><td>'+key+'</td><td>'+value+'</td></tr>');
});
console.log(table);
Upvotes: 2
Views: 4612
Reputation: 27232
Try this in JavaScript:
var resData = {"key1":"value","key2":"value"};
var table = '<table><thead><tr><th>Filter</th><th>Values</th></tr></thead>';
table += '<tbody>';
for (var i in resData) {
table += '<tr><td>'+i+'</td><td>'+resData[i]+'</td></tr>';
}
document.getElementById("table").innerHTML = table;
table,th,td { border: 1px solid black; }
<div id="table">
</div>
Upvotes: 0
Reputation: 6112
You're printing the jQuery object directly to the console. I presume you need the html content of the table. You need to use console.log(table.html())
. See the html() docs
Upvotes: 0
Reputation: 34924
Simply you can make like this.
var resData = {"key1":"value","key2":"value"};
var table_str = '<table><thead><tr><th>Filter</th><th>Values</th></tr></thead>';
table_str += '<tbody>';
$.each(resData, function(key, value){
table_str +='<tr><td>'+key+'</td><td>'+value+'</td></tr>';
});
$("#content").html(table_str);
console.log(table_str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>
Upvotes: 3
Reputation:
You can add a varible and concatinate it with value and then append to html
var resData = {"key1":"value","key2":"value"};
var table='<table><thead><tr><th>Filter</th><th>Values</th></tr></thead><tbody><tbody/>';
$.each(resData, function(key, value){
table+='<tr><td>'+key+'</td><td>'+value+'</td></tr>';
});
table+='</table>';
$('<html/>').append(table);
console.log(table);
Upvotes: 0
Reputation: 31
first create complete table html in var table
and then append table to body
Upvotes: 1