Loop JSON using JavaScript and create dynamic HTML table - javascript

I'm trying to loop through a JSON object from a REST endpoint. I've successfully iterated through the JSON array and created a dynamic table based on the variables I created from the JSON object.
The issues I'm having is creating a separate table for each location. For example, I would like each location to be their own row, and the associated camera position with its photo as separate cells. Instead, my table is coming out as one column, one row.
Here is what my code looks like (please disregard my amateur coding abilities, as I'm still learning) :) :
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function createLocationTable() {
var features = getAllLocations();
var site_number = '';
var sitename = '';
var cameraPostion = '';
var imgURL = '';
var date = new Date();
var content = '';
content = '<table align="center">';
content += '<tr><th class="table-header">';
content += '<center>RWIS Images</center></th></tr></table>'
content += '<table><tbody>';
var tempSiteName = features[0].attributes.SITE_NUMBER;
content += '<tr>';
for (var i = 0; i < features.length; i++) {
site_number = features[i].attributes.SITE_NUMBER
sitename = features[i].attributes.RPUID_NAME;
cameraPostion = features[i].attributes.CAMERA_POSITION;
imgURL = features[i].attributes.IMAGE_URL;
//if(tempSiteName.toString().substr(0,tempSiteName.toString().indexOf(' ')) != sitename.toString().substr(0,sitename.toString().indexOf(' ')))
if (tempSiteName != sitename) {
//then create a new row
tempSiteName = sitename;
content += '</tr>';
content += '<tr>';
}
//otherwise everythind goes side to side
content += '<td><center><b><br>' + sitename + '</b> -</br></center><center>' + cameraPostion +'</center>';
content += '<div><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +
' class="imgRWIS" height="100" width="150"></center></div></td>';
}
content += '</tbody></table>';
document.write(content)
return content;
}
window.onload = createLocationTable();
body {
font-family: Arial, 'Trebuchet MS', Verdana, Helvetica, sans-serif;
}
.table-header {
font-size: 24px;
font-family: Arial, sans-serif;
color: #d46200;
}
.sitename h{
font-size: 20px;
font-family: Arial, sans-serif;
color: #7c9f3d;
}
.table-location {
/* background: #dddddd; */
width: auto;
margin: 10px 0;
font-size: 14px;
border: 1px solid black;
}
.table-location td {
padding: 5px;
}
img.imgRWIS {
background: black;
position: relative;
padding: 1px;
display: block;
margin: 0 auto;
}

From what i understand this is what you want
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function createLocationTable() {
var features = getAllLocations();
var site_number = '';
var sitename = '';
var cameraPostion = '';
var imgURL = '';
var date = new Date();
var content = '';
content = '<table class="table-location"><tbody>';
content += '<tr><th class="table-header">';
content += '<center>Images</center></th></tr>';
var tempSiteNumber = features[0].attributes.SITE_NUMBER;
content += '<tr>';
content += '<tr><th class="table-header">';
content += '<center>' + features[0].attributes.RPUID_NAME + '</center></th></tr>';
for (var i = 0; i < features.length; i++) {
site_number = features[i].attributes.SITE_NUMBER
sitename = features[i].attributes.RPUID_NAME;
cameraPostion = features[i].attributes.CAMERA_POSITION;
imgURL = features[i].attributes.IMAGE_URL;
if (tempSiteNumber != site_number)
{
//then create a new row
tempSiteNumber = site_number;
content += '</tr>';
content += '<tr>';
content += '<tr><th class="table-header">';
content += '<center>'+sitename+'</center></th></tr>';
}
//otherwise everythind goes side to side
content += '<td>' + cameraPostion;
content += '<div><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +' class="imgRWIS" height="125" width="250"></center></div></td>';
}
content += '</tbody></table>';
document.write(content)
return content;
}
window.onload = createLocationTable();
body {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
.table-header {
background: #D07D0E;
}
.table-location {
/* background: #dddddd; */
width: auto;
margin: 10px 0;
font-size: 14px;
border: 1px solid black;
}
.table-location td {
padding: 5px;
}
img.imgRWIS {
background: black;
position: relative;
padding: 1px;
display: block;
margin: 0 auto;
}
<!doctype HTML>
<html>
<head>
<script src="test.js"></script>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
</body>
</html>
All you had to do is manage different "names", skip a line when it's different, otherwise all goes on the same line
EDIT
In order to have title over images you have to use a display block container like a Div.
There you go, all problems fixed.

The issue is your <tr> tag.
content += '<tr><td><b>' + sitename + '</b> - ' + cameraPostion + '</td>';
content += '<td><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +' class="imgRWIS" height="125" width="200"></center></td></tr>';
The content inside <tr> and </tr> makes for one row.
The content inside <td> and </td> makes for one column.

Related

Trouble with script-generated dynamic html element

I developing comment section for my HTMl page. I place it in div container in body section in my page, like that:
<body>
...
<div id='commentsTree'></div>
...
</body>
Commment section generated by script, here it is
function createCommentsTree(commentsData) {
resultHTML = "";
let commentsArray = JSON.parse(commentsData);
//let result = "";
resultHTML = resultHTML + "<ul id='myUL'>";
commentsArray.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
});
resultHTML = resultHTML + "</ul>";
return resultHTML;
}
function createCommentsTreeHyerarchycally(source) {
resultHTML = resultHTML + "<ul class='nested'>";
source.subordinates.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
})
resultHTML = resultHTML + "</ul>";
}
in result i have hyerarchycally comments tree, you can see it on example here
https://jsfiddle.net/Obliterator/wogurs6L/, or, on picture "comment section" added below.
On picture you can see "caret" symbol, looks like black small arrow near textareas, i mark it on picture. When i click it, comment line must unfold, and show subordinate comment lines. You can try it in example here https://jsfiddle.net/Obliterator/wogurs6L/, in this example it works totally correct. But, in my web page, when i click on "caret" symbol, nohing happens, comment line do not unfold. And this is a problem.
For unfold by clicking "caret" symbol i make this script and css:
script:
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
css:
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
.textFieldRoot {
position: relative;
left: 15px;
width: 100%;
}
.textField {
position: relative;
width: 100%;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
position: absolute;
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
vertical-align: top;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
i add css and script in my page, for which i trying add comment section, that way (treeListScript.js and treeListStyle.css):
<head>
...
<script type="text/javascript" src="http://localhost/testapp/lib/others/treeList/treeListScript.js"></script>
<link rel="stylesheet" href="http://localhost/testapp/lib/others/treeList/treeListStyle.css">
...
</head>
<body>
...
<div id='commentsTree'></div>
...
</body>
i create my web page this way:
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
line windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments); creates comment section.
So, what i am doing wrong, what i mus do for my unfold fucntional works correct on my web page? If something unclear, ask, i try explain.
I solve problem by myself. Reason is i just incorrect add event handler to the .caretelements, i add it as script in head section, but i need to add it after i generate comment section, this way:
//creating new HTML page +++
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
//creating new HTML page ---
//creating comment section +++
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
//creating comment section ---
//adding event handler +++
var toggler = windowTask.document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
//adding event handler ---
now everything works fine. If anyone spend some time for my question, thx.

Read formatted text from form through javascript

class Storedata {
constructor(name, desc, price, qty) {
this.name = name;
this.desc = desc;
this.price = price;
this.qty = qty;
}
}
var arr = [];
var btnform = document.getElementById('clicktoadd');
var btnlist = document.getElementById('clicktoshow');
var rem = document.getElementById('main');
var cancelform;
var submit;
function addData() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
arr.push(new Storedata(proname.value, prodesc.value, propric.value, proqty.value));
}
function showlist() {
var data = document.createElement('table');
data.setAttribute("id", "data");
data.innerHTML += "<tr><th>Product Name</th><th>Description</th><th>Price</th><th>Quantity</th><th></th></tr>";
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
document.getElementById('listing').appendChild(data);
document.getElementById('showbutton').removeAttribute("hidden", false);
}
function removelist() {
var data = document.getElementById("data");
data.parentNode.removeChild(data);
}
function addformtopage() {
var form = document.createElement('div');
form.setAttribute("id", "remform");
form.innerHTML += "<div id=\"lblname\">Product Name:</div><input id=\"inpname\" type=\"text\"><div id=\"chkname\" hidden=\"true\">Enter a Product Name</div><div id=\"lbldesc\">Description:</div><textarea id=\"inpdesc\" rows=\"10\" cols=\"35\"></textarea><div id=\"chkdesc\" hidden=\"true\">Enter a Product Desciption</div><div id=\"lblprice\">Price in INR:</div><input id=\"inpprice\" type=\"number\"><div id=\"chkprice\" hidden=\"true\">Enter a Product Price</div><div id=\"lblqty\">Quantity:</div><input id=\"inpqty\" type=\"number\"><div id=\"chkqty\" hidden=\"true\">Enter a Product Quantity</div><br><br><button id=\"submitproduct\">Submit</button><button id=\"cancel\">Cancel</button>";
document.getElementById('panel').appendChild(form);
cancelform = document.getElementById('cancel');
submit = document.getElementById('submitproduct');
}
function validateform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
var errname = document.getElementById("chkname");
var errdesc = document.getElementById("chkdesc");
var errpric = document.getElementById("chkprice");
var errqty = document.getElementById("chkqty");
if ((proname.value) && (prodesc.value) && (propric.value) && (proqty.value)) {
errname.setAttribute("hidden", true);
errdesc.setAttribute("hidden", true);
errpric.setAttribute("hidden", true);
errqty.setAttribute("hidden", true);
return true;
}
if (proname.value) {
errname.setAttribute("hidden", true);
}
if (prodesc.value) {
errdesc.setAttribute("hidden", true);
}
if (propric.value) {
errpric.setAttribute("hidden", true);
}
if (proqty.value) {
errqty.setAttribute("hidden", true);
}
if (!proname.value) {
errname.removeAttribute("hidden", false);
}
if (!prodesc.value) {
errdesc.removeAttribute("hidden", false);
}
if (!propric.value) {
errpric.removeAttribute("hidden", false);
}
if (!proqty.value) {
errqty.removeAttribute("hidden", false);
}
return false;
}
function clearform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
proname.value = null;
prodesc.value = null;
propric.value = null;
proqty.value = null;
}
function removeform() {
var elem = document.getElementById("remform");
elem.parentNode.removeChild(elem);
}
function removebuttons() {
rem.setAttribute("hidden", true);
}
function showbuttons() {
rem.removeAttribute("hidden", false);
}
btnform.addEventListener('click', function() {
addformtopage();
removebuttons();
cancelform.addEventListener('click', function() {
showbuttons();
removeform();
});
submit.addEventListener('click', function() {
if (validateform()) {
alert("Values Added");
addData();
clearform();
}
});
});
btnlist.addEventListener('click', function() {
showlist();
removebuttons();
document.getElementById('showbutton').addEventListener('click', function() {
showbuttons();
removelist();
document.getElementById('showbutton').setAttribute("hidden", "true");
});
});
#chkname,
#chkdesc,
#chkprice,
#chkqty {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 70%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet" />
<title>
JS Form
</title>
</head>
<body>
<div id="main">
<p><button id="clicktoadd">Add Product</button> <button id="clicktoshow">Show List</button></p>
</div>
<div id="panel">
</div>
<div id="listing">
</div>
<button id="showbutton" hidden="true">< Back</button>
<script src="script.js"></script>
</body>
</html>
I want to take input in form for description of the item as formatted text. And then output it in the same format as input, but right now I am getting text separated by space where should be there. Please help..
Steps to perform
1. Run this code snippet.
2. Click on 'Add Product' button.
3. Fill the form (For testing give a description of more than one line) and Submit.
4. Click on 'Cancel' button to return.
5. Click on 'Show List' button.
6. Observe Description column.
This is output I am getting separated by spaces
This is form input I am providing
Well, you have two options. Add a <pre> tag:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td><pre>" + arr[i].desc + "</pre></td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
This way it will display the new lines and you keep your string clean.
Or you can replace the new lines with <br> this way:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc.replace(/\n/g, "<br>") + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
Remember that the new lines are not shown by default in HTML, if you want a new line put a <br>
Test it online
Hope it helps! :)
Add this into your code:
var text = arr[i].desc;
text = text.replace(/\n/g, '<br />');
JSfiddle
See JavaScript: How to add line breaks to an HTML textarea? too.

Moving Javascript variables into Html Table

i found this guide to create a stock ticker.
I tried to change it into an html table, but i'm stuck.
So, i created the table, but i have big problems to divide each variable.
What i want to accomplish is a table with this columns order:
Symbol: CompName
Price: Price
Change: PriceIcon + ChnageInPrice
%: PercentChnageInPrice
What i've accomplished for now it's just this, all the content in one column (because of the variable StockTickerHTML i guess)
Full Code Link
Can you please help me?
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerHTML = "";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function () {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function () {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function () {
Price = $(this).text();
});
$(this).find("Change").each(function () {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function () {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText", PriceIcon="up_green";
if(parseFloat(ChnageInPrice) < 0) { PriceClass = "RedText"; PriceIcon="down_red"; }
StockTickerHTML = StockTickerHTML + "<span class='" + PriceClass + "'>";
StockTickerHTML = StockTickerHTML + "<span class='quote'>" + CompName + " </span> ";
StockTickerHTML = StockTickerHTML + parseFloat(Price).toFixed(2) + " ";
StockTickerHTML = StockTickerHTML + "<span class='" + PriceIcon + "'></span>" + parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + " (";
StockTickerHTML = StockTickerHTML + parseFloat( Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%)</span> </br>";
});
$("#dvStockTicker").html(StockTickerHTML);
$("#dvStockTicker").jStockTicker({interval: 30, speed: 2});
});
}
One solution could be this :
(see comments in code)
$(window).load(function() {
StockPriceTicker();
setInterval(function() {
StockPriceTicker();
}, 2 * 1000); // <------ we refresh each 2 seconds
});
// we get the table's body where
// the lines will be inserted.
var $body = $('table tbody');
/*
this will be the cache of
our lines, once they are prepared / transformed
as your need, we will join and insert them
in the body of our table.
*/
var Lines = [];
/*
We define a function in charge of creating the HTML
of each row of hour table, and then push them
in the array defined above "Lines".
*/
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// this is your function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
/*
We create the html to be inserted on each xml loop.
- First : prepare and transform as you need
- Last : use the function we define above "addLine";
*/
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='" + PriceClass + "'>";
htmlSymbol = htmlSymbol + "<span class='quote'>" + CompName + " </span></span>";
htmlPrice = parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// We use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
/*
Once the loop of reading the XML
end, we have pushed all html in the array "Lines".
So now we delete the content of our table's body, and
we fill it with all the lines joined.
*/
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
.GreenText {
color: Green;
}
.RedText {
color: Red;
}
.up_green {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/up.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
.down_red {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/down.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
table {
border: solid;
border-color: #666;
}
td {
padding: 3px;
}
.symbol {
border: solid 3px #DDD;
}
.price {
border: solid 3px aqua;
}
.change {
border: solid 3px yellow;
}
.percent {
border: solid 3px purple;
}
td.price,
td.change,
td.percent {
text-align: right;
}
tbody tr:nth-child(odd){
background-color:#EEF;
}
tbody tr:nth-child(even){
background-color:#AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class='symbol'>Symbol</th>
<th class='price'>Price</th>
<th class='change'>Change</th>
<th class='percent'>%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

getJSON JSON Array - Search Functionality Crashing Client

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

How to load a JSON string from an external URL onto a Chrome extension

I'm new to Chrome Extension development, so please help me with it.
I'm trying to read a JSON String from this URL
http://www.roblox.com/catalog/json?Subcategory=16&SortType=3&ResultsPerPage=10
And I want to display the result on a HTML Table on the browser_action.html popup.
I know this a very generic question, but it would help me if you could guide me.
After a little browsing, I found a step-by step guide on W3School
I used this tool to create the template : Extensionizr
And I just added a Popup.js into the same folder as browser_action.html
Inside Popup.js :
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/Customers_MYSQL.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
Inside browser_action.html :
<!doctype html>
<style type="text/css">
#mainPopup {
padding: 10px;
height: 200px;
width: 400px;
font-family: Helvetica, Ubuntu, Arial, sans-serif;
}
h1 {
font-size: 2em;
}
</style>
<script src=popup.js></script>
<div id="mainPopup">
<div id="id01"></div>
And that's it :)

Categories

Resources