I have JSON data like this:
[0:{name:"jason",height:"150cm"},
1:{name:"henry",height:"178cm"}]
I'm trying to do a for loop in my function, which is
function DrawTable(output) {
var general = output;
var sb = new StringBuilder();
for (var i = 0; i < *total row in the json*; i++)
sb.append("<td>" + general[0][i]["name"] + "</td>");
sb.append("<td>" + general[0][i]["height"] + "</td>");
}
I don't know the way to do it..
First off: that data isn't JSON.
For the sake of argument, let's pretend it was formatted as such:
[{
"name": "jason",
"height": "150cm"
}, {
"name": "henry",
"height": "178cm"
}]
Which would be valid JSON.
You could then do something more like this:
If using jQuery:
function DrawTable(jsonString) {
var stuff = JSON.parse(jsonString);
var table = createElement('table')
.append(
createElement('thead')
.append(
createElement('tr')
.append(
createElement('th').text('Name'),
createElement('th').text('Height')
)
)
);
var body = createElement('tbody');
stuff.forEach(function(item) {
body
.append(
createElement('tr')
.append(
createElement('td').text(item.name),
createElement('td').text(item.height)
)
);
});
//append body to table and show on page somewhere
}
Or, based on your existing code:
function DrawTable(output) {
var general = JSON.parse(output);
var sb = new StringBuilder();
for (var i = 0; i < general.length; i++) {
sb.append("<td>" + general[i].name + "</td>");
sb.append("<td>" + general[i].height + "</td>");
}
}
If your data happens to be formatted like:
{
0: {name:"jason",height:"150cm"},
1: {name:"henry",height:"178cm"}
}
instead of wrapped in an array. Then looping through Objects.values(yourData) might be what you are looking for:
function DrawTable(objectsData) {
var htmlString = '';
Object.values(objectsData).forEach((object) => {
htmlString += "<td>" + object.name + "</td>";
htmlString += "<td>" + object.height + "</td>";
});
return htmlString;
}
Related
Hie i am practicing XML , Javascript. I want to display image for each animal in a row. But my main problem arises uneven nesting in images . Some have two images while some have 4. I have XML File as follows:
<zoo>
<animal>
<common_name>Elephant</common_name>
<images>
<image>elephant13.jpg</image>
</images>
</animal>
<animal>
<common_name>Emu</common_name>
<images>
<image>emu12.jpg</image>
<image>emu26.jpg</image>
<image>emu23.jpg</image>
</images>
</animal>
<animal>
<common_name>Lion</common_name>
<images>
<image>lion51.jpg</image>
<image>lion46.jpg</image>
</images>
</animal>
<zoo>`
My javascript for img is :
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
images.src ="images/" + zooRoot.getElementsByTagName("image")[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
Try this. This get's the document node of xml and queries for images from it. Once you have the array, you iterate over it and get the inner text from the node.
var xmlimages = xml.getElementsByTagName('image');
for(var i=0; i< xmlimages.length; i++) {
images.src = "images/" + xmlimages[i].innerHTML.trim(); // trim used to remove all the white space from text that you get when you use innerHTML
}
Please insert loop on node:
for(var y = 0; y < noOfImages ; y++)
{
if (images)
{
var imgData = zooRoot.getElementsByTagName("image");
for (i = 0; i <imgData.length; i++) {
images.src ="images/" + imgData[i].firstChild.nodeValue;
ul.appendChild(images);
}
}
}
Try to get Animal as an object, then create a HTMLstring and insert it in node;
var animalsNode = zooRoot.getElementsByTagName('animal');
var animals = [];
for(var i=0; i<animalsNode.length; i++){
var animalName = animalsNode[i].getElementsByTagName("common_name").innerHTML;
var animalImageNodes = animalsNode[i].getElementsByTagName("image");
var animalImages = [];
//will store image paths into animalImages
for(var j=0; j<animalImageNodes.length; j++){
animalImages.push("image/" + animalImageNodes.innerHTML);
}
animals.push({
common_name: animalName,
images: animalImages //array of image urls
})
}
var animalsHTML = function(animals){
//lets cereate string with "html table"
var animalsHtml = "<table>";
for(var i=0; i<animals.length; i++){
animalsHtml += "<tr>";
animalsHtml += "<td>" + animals[i].name + "</td>"
+ "<td><img src='" + animals[i].images[0] + "' /></td>";
animalsHtml += "</tr>";
}
animalsHtml += "</table>";
return animalsHtml;
}
tableNode.innerHTML = animalsHTML(animals);
or you can define animal array more functional way =)
var animals = zooRoot.getElementsByTagName('animal').map(function(animalNode){
return {
common_name: animalNode.getElementsByTagName('common_name')[0].innerHTML,
images: animalNode.getElementsByTagName('image').map(function(imageNode){
return "image/" + imageNode.innerHTML;
})
};
});
//and more js style of draw-function
var animalsHTML = function(animals){
return "<table>" + animals.reduce(function(curr, next){
return curr + "<tr><td>" + next.name + "</td>"
+ "<td>"
+ next.images.reduce(function(c, n){
return c + "<img src='" + n "' />"
},'')
+ "</td>"
+ "</tr>";
}, '') + "</table>";
}
tableNode.innerHTML = animalsHTML(animals);
I didn't test it, but it should work.
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]);
}
});
I have created dynamically some select controls(a.k.a. groupbox) but every time that I try to access to one of them if get the followig error:
Uncaught TypeError: undefined is not a function
Here is the code:
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
Where parseInt(buttonElementId + 1 is always a number so the error is not there
<html>
<head lang="en">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
html, body, #wrapper
{
width: 100%;
height: 100%;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="container">
<div id="information"></div>
<div id="tableInformation"></div>
<div id="goBack"></div>
<br/>
<div id="inputDiv"></div>
<br/>
<br/>
<div id="UserGuide"></div>
</div>
<script src="js/jquery-1.11.js"> </script>
<script>
var apiUrl = 'http://localhost/devices';
$( document ).ready(function() {
// Handler for .ready() called.
jsonGETRequest(apiUrl, jsonExampleData);
});
$(document).on('click', ':button' , function() {
// reference clicked button via: $(this)
$("#UserGuide").empty();
var buttonElementId = $(this).attr('id');
if(buttonElementId.indexOf("btnShowFunc") > -1) {
buttonElementId = buttonElementId.replace("btnShowFunc","");
deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
} else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
switch (goBack) {
case "firstAPIRequest":
goBack = "";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl, jsonExampleData);
removeGoBackInputDiv();
break;
case "secondAPIRequest":
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
removeGoBackInputDiv();
break;
}
}else if(buttonElementId.indexOf("btnRunFunc") > -1) {
goBack = "secondAPIRequest";
buttonElementId = buttonElementId.replace("btnRunFunc","");
var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
$("#tableInformation tbody").remove();
$("#inputDiv").empty();
// /jsonPOST(apiUrl '/functions/' + functionUID )
}
});
function loadDataIntoDeviceGrid(jsonData) {
//$("#tableInformation").addClass("table table-responsive table-bordered");
var tbl=$("<table/>").attr("id","mytable");
$("#tableInformation").append(tbl);
$("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
+ "<th>dal.device.driver</th>" + "<th>service.id</th>" +"<th></th>" + "</tr>");
for(var i=0;i<jsonData.length;i++)
{
var tr = "<tr>";
var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";
//#Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); #Deprecated
var btn = "<td>" + "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );
}
$("#mytable").addClass("table table-responsive table-bordered");
}
function loadInformationDeviceGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
"Using this request, you can retrieve a list of all the available devices."+
"For every device, among other info, there is the indication of the device unique ID, which" +
"can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
}
function removeGoBackInputDiv() {
$("#inputDiv").empty();
$("#btnGoBack").remove();
}
function loadDataIntoFunctionsGrid(jsonData) {
$("#mytable").append("<tr>" + "<th>function.device.UID</th>"
+ "<th>service.id</th>" + "<th>function.UID</th>" + "<th>operation.names</th>" + "<th></th>" + "</tr>");
var tr, td2, td3, td4, dt2, btn;
for(var i = 0; i < jsonData.length; i++) {
tr = "<tr>";
//#Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
//#Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
btn = "<td>" + "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
$("#mytable").append(tr + td2 + td3 + td4 + dt2 + btn );
}
createGoBackButton();
createInputTextParameters();
}
function loadInformationFunctionsGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
+ "This API is used to retrieve the list of the available functions supported by the device. For"
+ "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
+ "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
+ "indicates the id, which can be used to access directly the function and the list of the operation"
+ "that can be invoked on the function.<br/>"
+ "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
+ "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
}
function createGoBackButton() {
var btn = '<button id="btnGoBack" class="btn btn-warning btn-lg">Go Back</button>';
$("#goBack").append(btn);
}
function createInputTextParameters() {
var lbl ="<label>Paramters</label>";
var txt ='<input type="text" class="form-control" name="email">';
$("#inputDiv").addClass("form-group");
$("#inputDiv").append(lbl);
$("#inputDiv").append(txt);
}
function fillSelectControl(obj, id) {
var dataList = "<td><select id='slt"+ id +"'>";
for(var j = 0; j < obj.length; j++)
dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
return dataList = dataList + "</select></td>";
}
var json = "";
var goBack = "";
var deviceUID;
function jsonGETRequest(url, dataExample){
$.getJSON(apiUrl, function(data) {
alert(JSON.stringify(data));
this.json = data;
})
.done(function() {
$("#information").addClass("alert alert-success");
$("#information").text("getJSON request succeeded!");
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationDeviceGrid();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
//alert('getJSON request failed! ' + textStatus);
$("#information").addClass("alert alert-danger");
$("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationFunctionsGrid();
} else if(goBack=="secondAPIRequest") {
}
})
.always(function() { });
}
function jsonPOST(url, method, paramters, dataExample) {
}
var jsonExampleData = [
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test123",
"dal.device.driver": "ZigBee",
"service.id": 28,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test456",
"dal.device.driver": "ZigBee",
"service.id": 29,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test789",
"dal.device.driver": "ZigBee",
"service.id": 30,
"objectClass": [
"org.osgi.service.dal.Device"
]
}
];
var jsonExampleDataFunctions = [
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test123",
"service.id": 27,
"dal.function.UID": "ZigBee:test123:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test456",
"service.id": 26,
"dal.function.UID": "ZigBee:test456:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test789",
"service.id": 25,
"dal.function.UID": "ZigBee:test789:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
}
];
</script>
</body>
</html>
.is() returns a true/false value, it does not continue the jQuery chain, therefor there is no .text() function to call
As DevishOne points out in the comments to get the selected option's text do:
=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();
Split that in to multiple steps and check for the particular result:
button = $("#slt" + (parseInt(buttonElementId + 1)));
if ( button )
{
childs = button.children("option");
if ( childs .....
Whenever there's no option selected, you are unable to catch that since you refer directly to a method .text() of null.
I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE
I am a newbie with json arrays/objects. I am trying to get to some subobjects within my .json file. I have tried the suggestions on here, but I keep getting "undefined" results. Here is the .json --
{
"DACcourses": [
{
"longTitle": "<a href='#'>Ammo-29 Electrical Explosives Safety for Naval Facilities</a>",
"longDescript": "ammo-29.html",
"atrrsLink": "Win 95+",
"delMeth": "standard",
"sked": [
{
"classNumb": "926",
"startDate": "4/16/2012",
"endDate": "4/20/2012",
"location": "NMC Fort Worth, TX",
"status": "scheduled",
"emptySeats": "Availability"
},
{
"classNumb": "001",
"startDate": "6/4/2012",
"endDate": "6/8/2012",
"location": "McAlester, OK",
"status": "scheduled",
"emptySeats": "Availability"
},
{
"classNumb": "920",
"startDate": "6/18/2012",
"endDate": "6/22/2012",
"location": "Belle Chasse, LA",
"status": "scheduled",
"emptySeats": "Class Full"
}
]}
]}
I must be doing something fundamentally wrong. so here is my code. In the end I am trying to build table rows out of each of the 'sked' objects. But I am having problems with getting individual data elements to show in the console. Here has been my attempts:
$('#content').on("click", "#catList tbody tr", function() {
var aData = oTable.fnGetData( this );
console.log( aData );
var scheduleData = aData.sked;
var catLink = 'catalog/' + aData.longDescript;
$('#fullDescript').load(catLink, function() {
if (!$('#fullDescript #offerings')) {
$('.enrollBTN').hide();
};
if ($(scheduleData).length > 0) {
$(scheduleData).each(function() {
for(var i = 0; i < scheduleData.length; i++) {
/*var startDate = aData.sked.startDate[2];
var endDate = aData.sked.endDate[3];
var location = aData.sked.location[4];
var classNumb = aData.sked.classNumb[1];
var status = aData.sked.status[5];
var emptySeats = aData.sked.emptySeats[6];*/
//var item = scheduleData[i];
console.log( aData.sked.startDate[2] );
var html = "<tr>";
html += "<td>" + item.classNumb + "<\/td>";
//console.log( aData.sked[1].classNumb );
/*html += "<td>" + scheduleData.endDate + "<\/td>";
html += "<td>" + scheduleData.location + "<\/td>";
html += "<td>" + scheduleData.classNumb + "<\/td>";
html += "<td>" + scheduleData.status + "<\/td>";
html += "<td>" + scheduleData.emptySeats + "<\/td>";*/
html += "<\/tr>";
//return scheduleData;
};
$('#schedule tbody').append($(html));
});
};
});
$('#content').hide();
$('#fullDescript').show();
});
Any help is appreciated.
It seems like you would only need the each or for loop, but not both. It also looks like there's some confusion in there on whether to use item = scheduleData[i] or not. Try this:
if ($(scheduleData).length > 0) {
for(var i = 0; i < scheduleData.length; i++) {
var item = scheduleData[i];
var html = "<tr>";
html += "<td>" + item.endDate + "</td>";
// ... etc
html += "</td>";
}
}
Just as a PS, I'd recommend looking into a JS templating tool like Mustache.js. This would allow you to separate data from display template, so you could eliminate the parsing code. It would look something like this:
var template = "{{#sked}}<tr><td>{{endDate}}</td><td>{{location}}</td></tr>{{/sked}}";
var html = "<table>" + Mustache.render(template, aData) + "</table>";
I must be doing something fundamentally wrong
Yes you are.
When you use .each loop, you refer to the current element by this keyword. So you do not need the for loop. Or, if you want the for loop, you do not need the .each loop. In my opinion, use the for loop. .each is just an overhead in this case.
UPDATE: #dbaseman gave you exactly what you need :)
UPDATE 2: Please try the following code. Basically its same as that of dbaseman, but dbaseman's snippet missed closing the <tr> element.
if ($(scheduleData).length > 0) {
for(var i = 0; i < scheduleData.length; i++) {
var item = scheduleData[i];
var html = "<tr>";
html += "<td>" + item.endDate + "</td>";
// ... etc
html += "</tr>"; // should close the <tr> here
}
}