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);
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);
<table>..</table>
tag ?
– Niklesh Raut
Commented
Apr 19, 2017 at 6:47
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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>
first create plete table html in var table
and then append table to body
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);
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
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>