Creating a HTML Table from nested JSON using JQuery - javascript

I have a sample JSON like this:
}
"vehicles":"4door",
"cars": {
"Toyota":"Camry",
"Ford":"Explorer",
"Nissan":"Altima",
"Jeep":"Wrangler"
},
"color":"red"
}
I'm trying to make an HTML table with 2 columns called something like "Make" and "Model" using the sample JSON with JQuery using the "cars" array out of the JSON without taking the other items vehicles and color. The "Make" would be the keys of the JSON and the "Model" would be the values of the keys. I'm trying to get it to look something like this below but in a table format. Any help or advice would be greatly appreciated.
Make Model
Toyota Camry
Ford Explorer
Nissan Altima
Jeep Wrangler

Use Object.keys which will give an array of keysThen you can iterate it and get the key value from the object and use template literals to create a row and finally append to the table
let cars = {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
}
let getKeys = Object.keys(cars);
let row = '';
for (let i = 0; i < getKeys.length; i++) {
row += `<tr><td>${getKeys[i]}</td><td>${cars[getKeys[i]]}</td></tr>`
}
$('#carTable').append(row)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='carTable'>
</table>

Use Object.keys to get an array of the cars and loop through them using forEach loop. Using append in jquery append the row to the table
var data = {
"vehicles": "4door",
"cars": {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
},
"color": "red"
}
var str='';
Object.keys(data.cars).forEach(e => {
str+='<tr><td>' + e + '</td><td>' + data.cars[e] + '</td></tr>';
})
$('#data').append(str)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
<tr>
<td>Make</td>
<td>Model</td>
</tr>
</table>

You can also create your entire html from the script
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var html = ""
var json = {
"vehicles":"4door",
"cars": {
"Toyota":"Camry",
"Ford":"Explorer",
"Nissan":"Altima",
"Jeep":"Wrangler"
},
"color":"red"
}
html = "<table><thead><th><td>Make</td><td>Model</td></th></thead><tbody>"
for(var x in json.cars){
html+= "<tr><td>"+ x +"</td><td>"+ json.cars[x] +"</td></tr>"
}
html+="</tbody></table>"
$("#main").append(html)
});
</script>
</head>
<body>
<div id="main"></div>
</body>
</html>

Here I seen json format was not correct also get jsonObject.KeyName hold in variable then loop json that holds variable.
var obj = {"Toyota":"Camry", "Ford":"Explorer", "Nissan":"Altima", Jeep":"Wrangler"};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
After that you implement in html format.

var data = {
"vehicles": "4door",
"cars": {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
},
"color": "red"
};
var cars = data.cars; // for better performance if large table
var tableData = Object.keys(cars).map(item => '<tr><td>' + item + '</td><td>' + cars[item] + '</td></tr>').join('');
$('#main>table').append(tableData)
<div id="main">
<table>
<tr>
<td>Make</td>
<td>Model</td>
</tr>
</table>
</div>

Related

HTML table with qrcode as column; loading issues on tablet

I have a HTML table with QRcode as one of its column values; I use QRcode.min js library to convert the string to QRcode;
json = $.parseJSON(JSON.stringify(res.d));
// console.log('data ' , json);
$.each(json, function (i, item) {
// console.log(item.medicine);console.log(item.Medicine);
if (item.QrImg1 == null) {
td1 = $('<td>').text(' ');
} else {
td1 = $('<td>').qrcode({ width: 100, height: 100, text: item.QrImg1 })
}
if (item.QrImg2 == null) {
td2 = $('<td>').text(' ');
} else {
td2 = $('<td>').qrcode({ width: 100, height: 100, text: item.QrImg2 })
}
var $tr = $('<tr>').append(
$('<td style="width:30%">').text(item.Medicine),
$('<td>').text(item.BatchCode),
td1,
td2
).appendTo('#meds');
}
This is a pharmacy app, where in all the medicines along with their batch code(as QRCode) is displayed. They will have to do quick filter search on the medicine name so pagination wont help.
The issue is that I have around 6000+ row so while loading it takes time specially on a tablet. Is there some way I can get this loaded faster.
if you get the data one time from the server and you do search on client side from table then jquery.DataTables will help you filter rows https://datatables.net/
it has many options customize the view of table & functionality like sort / search / group
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</head>
<body>
<table id="example">
<thead>
<tr><th class="site_name">Name</th><th>Url </th><th>Type</th><th>Last modified</th></tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$("#example").dataTable({
"aaData":[
["Sitepoint","http://sitepoint.com","Blog","2013-10-15 10:30:00"],
["Flippa","http://flippa.com","Marketplace","null"],
["99designs","http://99designs.com","Marketplace","null"],
["Learnable","http://learnable.com","Online courses","null"],
["Rubysource","http://rubysource.com","Blog","2013-01-10 12:00:00"]
],
"aoColumnDefs":[{
"sTitle":"Site name"
, "aTargets": [ "site_name" ]
},{
"aTargets": [ 1 ]
, "bSortable": false
, "mRender": function ( url, type, full ) {
return '' + url + '';
}
},{
"aTargets":[ 3 ]
, "sType": "date"
, "mRender": function(date, type, full) {
return (full[2] == "Blog")
? new Date(date).toDateString()
: "N/A" ;
}
}]
});
</script>
</body>
</html>

Handlebars adding items to table template

I would like to add items from a database into a handlebars.js template.
My template looks like this:
<script id="some-template" type="text/x-handlebars-template">
<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">
<thead>
<th>Categories</th>
</thead>
<tbody>
{{#categories}}
<tr>
<td>{{categoryName}}</td>
</tr>
{{/categories}}
</tbody>
</table>
</script>
My JS looks like this:
$(document).ready(function() {
$.getJSON("categories.php", function(data) {
let source = $("#some-template").html();
let template = Handlebars.compile(source);
for (let i = 0; i < data.length; i++) {
var output = {
categories: [{
categoryName: data[i].name
}]
};
console.log(output.categories)
$("#sampleArea").html(template(output));
}
});
});
When i use $("#sampleArea").html(template(output)); it only adds the last item in my database. If i use $("#sampleArea").append(template(output)); however it makes two tables; one for each item in my database.
I also tried:
{{#each categories}}
<tr>
<td>{{categoryName}}</td>
</tr>
{{/each}}
but that didn't work either.
You are overwriting the output variable each time you iterate through an item. Try defining the output variable outside the for-loop and push to it inside the loop.
$(document).ready(function() {
$.getJSON("categories.php", function(data) {
let source = $("#some-template").html();
let template = Handlebars.compile(source);
var output = {
categories: []
};
for (let i = 0; i < data.length; i++) {
output.categories.push({
categoryName: data[i].name
});
}
console.log(output.categories)
$("#sampleArea").html(template(output));
});
});

How to add every 12 items of an array into one <tr> set?

I have an array that every 12 items belongs to one set of data (i want to print that set into one <tr>). For example if my array got 24 items. I want to print first 12th items in one <tr> and remaining in second <tr> and so on. Could any one tell me how this can be done.Thanks
example array :
var myArray = ["1","first","Mixed","http://www.somesite.com/12.jpg","chicago","http://www.somesite.com/countries/1.jpg","false","http://www.somesite.com/logos/87.jpg","http://www.somesite.com/logos/87.jpg","winter","summer","http://somesite.com/list/thumb.jpg"];
This is the way i construct the array:
$.each($xml.find('dict>string'), function (i) {
var keyName = $(this).text();
myArray.push(keyName);
}
example <tr> to be printed via javascript:
<tr id="1">
<td>1</td>
<td><img src="http://somesite.com/list/thumb.jpg" height="42" width="42"></td>
<td>
chicago<br>
<br></td></tr>
What you really need to do is restructure your data to use an array of objects where each object contains all the key value pairs for a single table row.
Now building the html is trivial.
While we're at it, let's get rid of that inline javascript on the link and use an event handler instead:
var myArray = [{
id: 1,
name: 'first',
type: 'Mixed',
season: 'winter',
season2: 'summer',
logo1: 'http://www.somesite.com/12.jpg&city=chicago',
logo2: 'http://www.somesite.com/countries/1.jpg',
logo3: 'http://www.somesite.com/logos/87.jpg',
logo4: 'http://www.somesite.com/logos/87.jpg',
order: false,
thumb: 'http://somesite.com/list/thumb.jpg',
city: 'chicago'
}, {
id: 1,
name: 'last',
type: 'someType',
season: 'fall',
season2: 'spring',
logo1: 'http://www.somesite.com/12.jpg&city=chicago',
logo2: 'http://www.somesite.com/countries/1.jpg',
logo3: 'http://www.somesite.com/logos/87.jpg',
logo4: 'http://www.somesite.com/logos/87.jpg',
order: true,
thumb: 'http://somesite.com/list/thumb.jpg',
city: 'new york'
}, ];
$.each(myArray,function(i, object){
var $row = $('<tr>');
$row.append( $('<td></td>', {text:object.id}));
$row.append( $('<td></td>').append( $('<img>', {src:object.thumb, height:42, width:42}))) ;
$row.append( $('<td></td>').append( $('<a></a>', {href:'#', text:object.city, class:'doIt'}).data(object)));
$('#myTable').append($row);
});
$('#myTable').on('click','.doIt',function(e){
// use this handler to access the data on the link
// put your logic from "doIt()" in here instead
e.preventDefault();
var $this=$(this);
console.log($this.data('name'));
console.log($this.data('type'));
console.log($this.data('season'));
// etc....
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
</table>
you can do it easily by spliting string. put your all data into a string, divide each 12 by special character like |, then divide inside strings from , and split it twice. below is a example and I used example data to understand. hope this will help to your. refere the working demo.
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#mytable
{
border-collapse: collapse;
}
table td{
border:1px solid black;
}
</style>
<body>
<table id='mytable'>
</table>
<script type="text/javascript">
var the_data = "1,first,mixed,http://www.first.com,chicago,http://www.somefirst.com/contry.jpg,http://www.somitemsone.com/logos/87.jpg,http://another.jpg,winter,summer,http://someitmeone/logo/one.jpg,http://oneone.com|2,22,2222,22222,22222,222222,22222222,22222222,222222222,222222222,22222222,22222222222";
var splited = the_data.split('|');
var create;
for (var i =0;i<splited.length;i++)
{
create = "<tr>";
var myarray = splited[i].split(',');
for(var j=0;j<myarray.length;j++)
{
var value = myarray[j];
create += "<td>"+value+"</td>";
}
create += "</tr>";
$("#mytable").append(create);
}
</script>
</body>
</html>
like above you can print your other data also. have a nice day

How to Represent JSON response in a table column wise

I am using the following code to receive a json as response and represent them in a table.
$(document).ready(function() {
var settings = {
"async" : true,
"crossDomain" : true,
"url" : "Parse",
"method" : "GET",
"headers" : {
"content-type" : "application/json"
},
"processData" : false
}
$.ajax(settings).done(function(jsnData) {
var obj = JSON.parse(jsnData);
for (var i = 0, len = obj.length; i < len; i++) {
var j=0;
var trd="";
trd +="<tr>";
trd+="<td>"
+ obj[i].word
trd+= " </td>";
trd+="<td>"
+ "<select class='input-small'><option value=''>"+obj[i].senses+"</option></select>";//obj[i].senses
trd+= " </td>";
trd+="</tr>";
$('#userdata tr:last').after(trd);
}
});
});
</script>
The userdata is the id o the table I am using to feed this json response.
The Json format is
[
{
"word": "play",
"senses": ["n1","n2","n3"]
},
{
"word": "play1",
"senses": ["m1","m2","m3"]
},
{
"word": "play2",
"senses": ["j1","k2","l3"]
},
{
"word": "play3",
"senses": ["x","ny","z"]
},
{
"word": "play4",
"senses": ["p","q","r"]
}
]
In my table there are two columns,One for word and one for senses,but I want the senses column as drop down.I am getting the output as follow,
As you can see,the Option column which I want to use to represent senses,showing the senses for the respected word in one line,e.g. for word play its senses are showed as n1,n2,n3.I want them to be shown as drop down,i.e. for for word play,drop down values will be n1 n2 and n3 for word play1,drop down values will be m1 m2 and m3.
HTML code
<table id="userdata" border="2">
<tr>
<td><b>Word</b></td>
<td><b>Options</b></td>
</tr>
<tbody>
</tbody>
</table>
I tried hard but was not been able to do it in desired way.any help would be much appreciated.
use this
+ "<select class='input-small'>";
for(var k=0; i <obj[i].senses.length;k++){
trd+="<option value='"+obj[i].senses[k]+"'>"+obj[i].senses[k]+"</option>";
}
trd+="</select>";

How do I render X <option>s in a <select>using jQuery.tmpl?

I'm inserting rows in a <table> that are bound to a JSON object. A cell in the table contains a <select> that needs to contain the number of objects, so 7 objects would produce 7 <option>s, 1-7.
Can this be done in the template definition?
Edit: I've added sample data and markup. From this data, I would want to add 3 <option>s (1-3) to the DisplayOrder <select> and have the appropriate <option> selected for each <select>.
Example: http://jsfiddle.net/4SxTS/
var data = [{
"Id": 1,
"DisplayOrder": 1,
"LabelText": "Unit On-Line Status:"},
{
"Id": 2,
"DisplayOrder": 2,
"LabelText": "AGC Pct:"},
{
"Id": 3,
"DisplayOrder": 3,
"LabelText": "Main Steam Heat Rate
}];
<table border="1" cellpadding="0" cellspacing="0">
<thead><tr><th>Display Order</th><th>Label Text</th></tr></thead>
<tbody></tbody>
</table>
<script id="attributeTemplate" type="text/x-jquery-tmpl">
<tr>
<td><select name="DisplayOrder"></select></td>
<td><input type="text" name="LabelText" value="${LabelText}" /></td>
</tr>
</script>
I'm not sure exactly what you mean without some sample data and markup, but I think the main part of your question deals with looping through numbers and rendering an option tag for each number. You could do this by creating an array containing "N" elements and then using {{each}}, but I think that using a custom template tag works well here:
Define a {{for}} tag that iterates through numbers 0 to n:
$.extend(jQuery.tmpl.tag, {
'for': {
open: "for(var $i = 0; $i < $1; $i++) {",
close: "}"
}
});
Use the new tag in a template:
<script type="text/html" id="row-tmpl">
{{each Rows}}
<tr>
<td>${Title}</td>
<td>${Description}</td>
<td>
<select>
{{for $data.TotalObjects}}
<option>${$i}</option>
{{/for}}
</select>
</td>
</tr>
{{/each}}
</script>
Called with:
var rows = {
TotalObjects: 5,
Rows: [{
Title: 'Test Row',
Description: 'Test Row Description'
},
{
Title: 'Another Row',
Description: 'Another Row Description'
}]
};
Best demonstrated in a working example: http://jsfiddle.net/xgE3Y/
Your situation might be even simpler, but my answer should enable you to at least use a simple for loop in a template and act on each iteration's value.
Maybe something like this:
$(function () {
var thisSelectObjects = 8;
var thatSelectObjects = 2;
$.fn.setOptions = function (options) {
var settings = {
'selectNum': 1
};
return this.each(function () {
if (options) {
$.extend(settings, options);
}
for (i = 0; i < settings.selectNum; i++) {
$(this).append('<option>' + i + '<option/>');
}
});
};
$('#thisSelect').setOptions({ 'selectNum': thisSelectObjects });
$('#thatSelect').setOptions({ 'selectNum': thatSelectObjects });
});
Html:
<body>
<select id='thisSelect'></select>
<select id='thatSelect'></select>
</body>

Categories