Parsing JSON objects for HTML table - javascript

I am trying to display a "leaderboard" table based on JSON data.
I have read a lot about the JSON format and overcome some initial obstacles, but my Javascript knowledge is very limited and I need help!
Basically my JSON data comes through looking like this:
[{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
What I need is to be able to loop through this array, generating a table row or list item for each object. There will be an unknown amount of total objects in the array but each will have the same format- three values: Name, Score, Team.
So far I have used the following code, which confirms that I am successfully loading the objects in the console-
$.getJSON(url,
function(data){
console.log(data);
});
but I am not sure how to iterate over them, parsing them into the HTML table.
The next step is sorting the entries by score in descending order...
Any help would be much appreciated.
Thanks!
EDIT:
Updated code below, this works:
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].User_Name + "</td>");
tr.append("<td>" + data[i].score + "</td>");
tr.append("<td>" + data[i].team + "</td>");
$('table').append(tr);
}
});
(The $.parseJSON was not necessary, we can use 'data' as the JSON array is already parsed I believe)

Loop over each object, appending a table row with the relevant data each iteration.
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').append(tr);
}
});
});
JSFiddle

You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<div jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{score}}</td>
</tr>
</div>
<table>
<tbody id="tbody">
</tbody>
</table>

Loop over each object, push in string array and join them. Append in target table, it is better.
$(document).ready(function () {
$.getJSON(url,
function (json) {
var tr=[];
for (var i = 0; i < json.length; i++) {
tr.push('<tr>');
tr.push("<td>" + json[i].User_Name + "</td>");
tr.push("<td>" + json[i].score + "</td>");
tr.push("<td>" + json[i].team + "</td>");
tr.push('</tr>');
}
$('table').append($(tr.join('')));
});

You can use KnockoutJS with jQuery. KnockoutJS have smart data-binding features. By using the foreach binding feature you can write your code like this example:
HTML:
<table>
<thead>
<tr>
<th>User Name</th>
<th>Score</th>
<th>Team</th>
</tr>
</thead>
<tbody data-bind="foreach: teams">
<tr>
<td data-bind="text: User_Name"></td>
<td data-bind="text: score "></td>
<td data-bind="text: team "></td>
</tr>
</tbody>
</table>
JavaScript:
$(document).ready(function () {
$.getJSON(url,function (json) {
ko.applyBindings({
teams: json
});
}
});
});
Fiddle Demo with your dummy data

Make a HTML Table from a JSON array of Objects by extending $ as shown below
$.makeTable = function (mydata) {
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
tblHeader += "</tr>";
$(tblHeader).appendTo(table);
$.each(mydata, function (index, value) {
var TableRow = "<tr>";
$.each(value, function (key, val) {
TableRow += "<td>" + val + "</td>";
});
TableRow += "</tr>";
$(table).append(TableRow);
});
return ($(table));
};
and use as follows:
var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");
where TableCont is some div

This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
Example:
var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")
$('#myDiv').html(myHtmlTableObj)
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='myDiv'>table goes here</div>

another nice recursive way to generate HTML from a nested JSON object (currently not supporting arrays):
// generate HTML code for an object
var make_table = function(json, css_class='tbl_calss', tabs=1){
// helper to tabulate the HTML tags. will return '\t\t\t' for num_of_tabs=3
var tab = function(num_of_tabs){
var s = '';
for (var i=0; i<num_of_tabs; i++){
s += '\t';
}
//console.log('tabbing done. tabs=' + tabs)
return s;
}
// recursive function that returns a fixed block of <td>......</td>.
var generate_td = function(json){
if (!(typeof(json) == 'object')){
// for primitive data - direct wrap in <td>...</td>
return tab(tabs) + '<td>'+json+'</td>\n';
}else{
// recursive call for objects to open a new sub-table inside the <td>...</td>
// (object[key] may be also an object)
var s = tab(++tabs)+'<td>\n';
s += tab(++tabs)+'<table class="'+css_class+'">\n';
for (var k in json){
s += tab(++tabs)+'<tr>\n';
s += tab(++tabs)+'<td>' + k + '</td>\n';
s += generate_td(json[k]);
s += tab(--tabs)+'</tr>' + tab(--tabs) + '\n';
}
// close the <td>...</td> external block
s += tab(tabs--)+'</table>\n';
s += tab(tabs--)+'</td>\n';
return s;
}
}
// construct the complete HTML code
var html_code = '' ;
html_code += tab(++tabs)+'<table class="'+css_class+'">\n';
html_code += tab(++tabs)+'<tr>\n';
html_code += generate_td(json);
html_code += tab(tabs--)+'</tr>\n';
html_code += tab(tabs--)+'</table>\n';
return html_code;
}

Here are two ways to do the same thing, with or without jQuery:
// jquery way
$(document).ready(function () {
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].User_Name + "</td>");
tr.append("<td>" + json[i].score + "</td>");
tr.append("<td>" + json[i].team + "</td>");
$('table').first().append(tr);
}
});
// without jquery
function ready(){
var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];
const table = document.getElementsByTagName('table')[1];
json.forEach((obj) => {
const row = table.insertRow(-1)
row.innerHTML = `
<td>${obj.User_Name}</td>
<td>${obj.score}</td>
<td>${obj.team}</td>
`;
});
};
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){
ready();
} else {
document.addEventListener('DOMContentLoaded', ready);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>'
<table>
<tr>
<th>User_Name</th>
<th>score</th>
<th>team</th>
</tr>
</table>

I spent a lot of time developing various reports. So, now I have an idea - create a web framework for building web reports. I have started here:
https://github.com/ColdSIce/ReportUI
Now it is an angular 4 module. You can pass your json data to TableLayoutComponent and get a HTML table as result. Table already has fixed header. Also you can fix some your columns by default or by click. More there, you can customize table properties like background-color, font-color, row-height etc.
If you are interested you can join me in this project and help.

Here is an another way to parse json object into Html table
//EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < d.length; i++) {
for (var key in d[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");// TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < d.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = d[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

This code will help a lot
function isObject(data){
var tb = document.createElement("table");
if(data !=null) {
var keyOfobj = Object.keys(data);
var ValOfObj = Object.values(data);
for (var i = 0; i < keyOfobj.length; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var key = document.createTextNode(keyOfobj[i]);
td.appendChild(key);
tr.appendChild(td);
tb.appendChild(tr);
if(typeof(ValOfObj[i]) == "object") {
if(ValOfObj[i] !=null) {
tr.setAttribute("style","font-weight: bold");
isObject(ValOfObj[i]);
} else {
var td = document.createElement('td');
var value = document.createTextNode(ValOfObj[i]);
td.appendChild(value);
tr.appendChild(td);
tb.appendChild(tr);
}
} else {
var td = document.createElement('td');
var value = document.createTextNode(ValOfObj[i]);
td.appendChild(value);
tr.appendChild(td);
tb.appendChild(tr);
}
}
}
}

For those interested in a general solution in plain Vanilla JS. It works independently of the number of columns you have in your json.
const myData = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
const createTable = (json) => {
let table = document.getElementById('js-table')
for (let row of json) {
let newRow = table.insertRow();
for (let cell of Object.values(row)) {
let newCell = newRow.insertCell();
let newText = document.createTextNode(cell);
newCell.appendChild(newText);
}
}
}
createTable(myData)
<table>
<tbody id="js-table">
</tbody>
</table>

This post is very much helpful to all of you
First Parse the json data by using jquery eval parser and then iterarate through jquery each function below is the code sniplet:
var obj = eval("(" + data.d + ")");
alert(obj);
$.each(obj, function (index,Object) {
var Id = Object.Id;
var AptYear = Object.AptYear;
$("#ddlyear").append('<option value=' + Id + '>' + AptYear + '</option>').toString();
});

Related

Populating HTML table with Google Sheet data (rows & columns)

Having issues with what it might be a rather easy fix.
Context: My code is currently pulling data from Google Sheets, crafting some sort of table and sending it back to HTML where it repopulates an already existing table.
Issue: I am unable to make it so that it builds columns as well as rows. It pastes the data back all in one go (see image for context).
Files: GS & HTML. I believe the issue is on how I'm crafting the table. I know the current disposition of '' doesn't make sense, bu
HTML table with Gsheet values:
Original Gsheet table:
Google Script
function populateStratTb2(){
var tablerows = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(1, 5, 1000).getValue();
var tablevalues = SpreadsheetApp.getActive().getSheetByName('supp_str').getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var active = SpreadsheetApp.getActive();
var sheet = active.getSheetByName("supp_str");
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for ( var r = 0; r < 10; r+=1) {
for (var i = 0; i < data.length; i+=1) {
optionsHTML += '<tr><td>' + data[i][r] + '</td></tr>';
}};
return optionsHTML;
}
HTML Script
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(displayData)
.populateStratTb2();
});
function displayData(hl){
document.getElementById('strattable').innerHTML=hl;
}
console.log('MyCode');
</script>
PS. I have spent a good couple hours scrolling though the forum picking bits and improving my original code. I am sure this question (or similar) has been answered already but I can't manage to find it.
In your script, how about the following modifications?
Modification 1:
If your for loop is used, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = "";
for (var r = 0; r < 10; r += 1) {
var row = "";
for (var i = 0; i < data.length; i += 1) {
row += '<td>' + data[i][r] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
return optionsHTML;
}
I'm worried that your for loop might not be your expected result. So, I would like to proposed one more modified script as "Modification 2".
Modification 2:
If your data is converted to the HTML table, how about the following modification?
function populateStratTb2() {
var sheet = SpreadsheetApp.getActive().getSheetByName('supp_str');
var tablerows = sheet.getRange(1, 5, 1000).getValue();
var tablevalues = sheet.getRange(4, 1, tablerows).getValues();
var tvlen = tablevalues.length
var myRange = sheet.getRange("d3:m" + tvlen);
var data = myRange.getValues();
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
return optionsHTML;
}
Note:
If you don't want to add the border, please modify <table border="1" style="border-collapse: collapse"> to <table>.
From your reply, I added 2 sample scripts for the script for obtaining the same result from reduce and for loop as follows.
reduce
var optionsHTML = '<table border="1" style="border-collapse: collapse">' + data.reduce((s, r) => s += "<tr>" + r.map(c => `<td>${c}</td>`).join("") + "</tr>", "") + "</table>";
for loop
var optionsHTML = "";
for (var r = 0; r < data.length; r++) {
var row = "";
for (var c = 0; c < data[r].length; c++) {
row += '<td>' + data[r][c] + '</td>';
}
optionsHTML += '<tr>' + row + '</tr>';
}
optionsHTML = '<table border="1" style="border-collapse: collapse">' + optionsHTML + "</table>";
Reference:
reduce()

Add rows to an empty tbody element

I have table like this:
<table id="search-table" class="table">
<thead>
<tr>
<th>Something</th>
<th>Something2</th>
<th>Something3</th>
<th>Something4</th>
<th>Something5</th>
</tr>
</thead>
<tbody></tbody>
</table>
I have an API call which returns data that I want to put as row and columns in the empty tbody element.
var body = document.getElementsbyTagName("tbody");
var x = 0;
for (i = 0; i < APIcall.length; i++) {
var createRow = body.insertRow();
for (j = 0; j < 7; j++) {
var x = createRow.insertCell(j);
}
}
If I insertRow on the thead element the rows are created, but not when I try to add it to tbody. Probably me just misunderstanding something. Any suggestions what I should do?
you're almost there.
First, as Rory mentioned, you're not targeting the tbody in DOM.
You can fix that by replacing the first line with this:
var body = document.querySelector('#search-table tbody')
What that does, is this: It looks for an element with an ID of search-table and a descendant <tbody> and returns a reference.
Your code would run without an error then, but I'm confused about the result.
In the second line, you have var x = 0 but later on I can see var x = createRow.insertCell(j); also. (The second x would give you a reference to a new <td> element).
Hope that helps.
var html ='';
for (i = 0; i < APIcall.length; i++) {`enter code hereenter code here
html += '<tr><td>' + APIcall[i].somthing + '</td><td>'+ APIcall[i].somthing + '</td>' +
'<td>' + APIcall[i].somthing + '</td>' + < td > '+APIcall[i].somthing+' </td>'+
'<td>' + APIcall[i].somthing + '</td></tr>';
}
$('#search-table > tbody').append(html);
enter code here
If you have more than one tbody in your markup, you have to target your's specifically because getElementsByTagName returns an array of elements.
for eyample:
var tbodies = document.getElementsbyTagName("tbody");
var targetTbody = tbodies[0];
or you could loop over tbodies if you want to add your stuff to multiple tbodies.

How do I include a header in a generated table of my javascript?

I receive in my javascript a json data that it is converted to a html table.
The script is working.. but how do I include a header in my table?
Here is the code:
<script>
$(document).ready(function(){
$('#id_adv').DataTable();
$('#id_adv').on('click','.btn',function(){
var currow = $(this).closest('tr');
var result = currow.find('td:eq(1)').text();
$.get('{% url "prop_table" %}', {var1:result}, function (data_prop) {
var data = data_prop['data_prop']
var data_json = JSON.parse(data);
var html = "";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
})
document.getElementById('total').innerHTML = result;
});
});
</script>
Slight modification to your existing code to add a header. (I've cut out your usage of eval and just kept in the relevant part to create the HTML table header)
<script>
....
var html = "";
html += "<tr><th>Header 1</th><th>Header 2</th><tr>";
for (var i = 0; i < data_json.length; i++) {
html += "<tr><td>" + data_json[i].fields.var1 + "</td><td>" + data_json[i].fields.var2 + "</td><tr>";
}
$('#id_prop').html(html);
....
</script>
This should add a header to your table.
And I agree with the comment in your question, use the built in JSON parsing. eval is just asking to be exploited.
I think that you can add the header after create the table. The createTHead() method creates an empty element and adds it to the table. I.e.:
<script>
function createHeader() {
var table = document.getElementById("myTable");
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "<b>This is a table header</b>";
}
</script>

Sorting data to the HTML tables by their ID jQuery/javaScript

I have an iteresting problem and I was trying to solve it for days.
I have a jQuery script which takes JSON object from the url and then put it into the array. The problem occurs when I have 3 different tables and script puts the data into 3 of them. I was trying to sort it by #id recognision, but it wasn't working at all.
This is a script which takes data from the server.
The JSON object is: [{"Date": 20160721, "Failures": 5, "Hostname": "AIX", "Scan policy": "compliance-rhel6-int-prd"}, {"Date": 20160721, "Failures": 1, "Hostname": "Linux", "Scan policy": "compliance-rhel6-int-prd"}]
Script:
<script>
var url = 'http://jsonobj/_server_data'
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].Date + "</td>");
tr.append("<td>" + data[i].Failures + "</td>");
tr.append("<td>" + data[i].Hostname + "</td>");
$('table').append(tr);
}
});
</script>
What I am trying t o do is create two tables one for AIX one for Linux and store the data for that systems only. Right now the same data appears in two tables.
I was t rying to sort it by getting $.(#hostname) as ID, but it didn't work.
Thank you for your help!
Just have 2 tables on the page. One with the id of #AIX and the other with the id of #Linux
HTML:
<table id="AIX"></table>
<table id="Linux"></table>
Javascript:
<script>
var url = 'http://jsonobj/_server_data'
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].Date + "</td>");
tr.append("<td>" + data[i].Failures + "</td>");
tr.append("<td>" + data[i].Hostname + "</td>");
// This is where the magic happens
$('table#' + data[i].Hostname).append(tr);
}
});
</script>
Doing this, the tr elements will be appended only to the table which matches the ID of the hostname.
This should do the trick:
var AIX = [], Linux = [];
var url = "http://jsonobj/_server_data";
$.getJSON(url, function(data) {
data = JSON.parse(data);
for(var x in data) {
if(data[x].Hostname == "AIX") {
AIX[AIX.length] = data[x];
} else if(data[x].Hostname == "Linux") {
Linux[Linux.length] = data[x];
}
}
printTables();
});
function printTables() {
var tableAIX = document.getElementById('tableAIX');
var newAIX = "";
var tableLinux = document.getElementById('tableLinux');
var newLinux = "";
for(var x in AIX) {
newAIX += "<tr><td>"+AIX[x].Date+"</td><td>"+AIX[x].Failures+"</td><td>"+AIX[x].Hostname+"</td></tr>";
}
for(var x in Linux) {
newLinux += "<tr><td>"+Linux[x].Date+"</td><td>"+Linux[x].Failures+"</td><td>"+Linux[x].Hostname+"</td></tr>";
}
tableAIX.innerHTML = newAIX;
tableLinux.innerHTML = newLinux;
}
With this as HTML:
<table id='tableAIX'></table>
<table id='tableLinux'></table>
Simple: iterate the tables.
$.getJSON(url, function (data) {
var tr;
for (var i = 0, $tables = $('table'), c; c = data[i]; i++) {
$tr = $('<tr/>');
$tr.append("<td>" + c.Date + "</td>");
$tr.append("<td>" + c.Failures + "</td>");
$tr.append("<td>" + c.Hostname + "</td>");
$tables[i].appendChild($tr[0]);
}
});

JavaScript loop won't separate <TD> elements

I am using JavaScript to fetch some XML data and loop it in a table. However the TD elements won't separate to a new line.
Here is my HTML:
<div id="gData">
<table class="tftable" border="1">
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
<tr>
<td class="gDate"></td>
<td class="gGame"></td>
<td class="gHome"></td>
<td class="gDraw"></td>
<td class="gAway"></td>
</tr>
</table>
</div>
and here is my JS:
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sports.sport.leagues.league.events.event;
for (var i = 0; i < game_data.length; i++) {
$('#gData .gGame').append( '<td>' + game_data[i].homeTeam.name + ' vs ' + game_data[i].awayTeam.name + '</td> ');
$('#gData .gDate').append( '<td>' + game_data[i].startDateTime) + '</td>';
$('#gData .gAway').append( '<td>' + game_data[i].periods.period[i].moneyLine.awayPrice) + '</td>';
$('#gData .gHome').append( '<td>' + game_data[i].periods.period[i].moneyLine.homePrice) + '</td>';
$('#gData .gDraw').append( '<td>' + game_data[i].periods.period[i].moneyLine.drawPrice) + '</td>';
}
};
The data comes back fine from the loop but displays all the dates in one TD, all the Games in the next TD.
You must also create your tr tags dynamically. Here's what I would suggest:
First make sure your table has a thead and tbody.
<table id="my-table">
<thead>
<th>Date</th>
<th>Game</th>
<th>Home</th>
<th>Draw</th>
<th>Away</th>
</thead>
<tbody></tbody>
<table>
Then you can generate your rows dynamically and append them to the tbody element. To save on writing i'll just give an example that isin't based on your code.
var $trs = $(document.createDocumentFragment()), //reduce DOM reflows
data = [{ a:1, b:2, c:3 }],
i = 0,
len = data.length,
rowData, $tr;
for (; i < len; i++) {
rowData = data[i];
$tr = $('<tr>'); //create your row
//append cells, you can also create a function to encapsulate
//that repetitive logic
$tr.append($('<td>').addClass('yourClass').text(rowData.a));
$tr.append($('<td>').addClass('yourOtherClass').text(rowData.b));
$tr.append($('<td>').addClass('yetAnotherClass').text(rowData.c));
//append the tr to the document fragment
$trs.append($tr);
}
//append the document fragment to the tbody
$('#my-table > tbody').append($trs);
It's remarkable how even the simplest task can be butchered by jQuery...
var table = document.getElementById('gData').children[0],
tbody = table.tBodies[0];
window['gCallback'] = function(data) {
var game_data = data.query.results.rsp.fd.sprts.sport.leages.leage.events.event,
len = game_data.length, i, tr;
table.removeChild(tbody);
for( i=0; i<len; i++) {
tr = document.createElement('tr');
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].homeTeam.name));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].startDateTime));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.awayPrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.homePrice));
tr.appendChild(document.createElement('td'))
.appendChild(document.createTextNode(game_data[i].periods.period[i].moneyLine.drawPrice));
tbody.appendChild(tr);
}
table.appendChild(tbody);
};
And this HTML:
<div id="gData">
<table class="tftable" border="1">
<thead>
<tr><th>Date</th><th>Game</th><th>Home</th><th>Draw</th><th>Away</th></tr>
</thead>
<tbody></tbody>
</table>
</div>
Note that you can simplify the above code with a helper function:
function addCellWithText(tr,text) {
return tr.appendChild(document.createElement('td')).appendChild(document.createTextNode(text));
}
Then your loop's contents become:
for(...) {
tr = document.createElement('tr');
addCellWithText(tr,game_data[i].homeTeam.name);
addCellWithText(tr,game_data[i].startDateTime);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.homePrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.awayPrice);
addCellWithText(tr,game_data[i].preiods.period[i].moneyLine.drawPrice);
tbody.appendChild(tr);
}

Categories