get all inherited properties by function in Javascript - javascript

without using funtion, when i use for (var prop in obj) which will show me all value in the object. However when i tried to put in function, it just show up me with the first value in the object which not show me the second element ( studentID ). :(
var target = document.getElementById("outputArea");
var outstring = " ";
var myObj = {
name: "Nguyen Viet Tien",
StudentID: "26813157",
};
function tellAll(obj) {
var dis = " ";
for(var prop in obj) {
dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";
return dis;
}
}
outstring += tellAll(myObj);
target.innerHTML = outstring;
<html lang="en">
<head>
<meta charset="utf-8">
<title>Eng1003 Workshop Code Week 04</title>
<style>
#outputArea {
padding: .25em;
border: solid black 2px;
margin: 3em;
height: 20em;
width: 20em;
overflow-y: scroll;
font-family: arial "sans serif";
font-size: 1em;
color: rgb(50, 50, 250);
background-color: rgb(225,225,225) ;
}
</style>
</head>
<body>
<div id="outputArea"></div>
</body>
</html>

return statement in the wrong place
function tellAll(obj) {
var dis = " ";
for(var prop in obj) {
dis += "first property is" + prop + "with the content" + obj[prop] + "<br/>";
}
return dis;
}

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.

Loop JSON using JavaScript and create dynamic HTML table

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.

Using Glyphicon button instead of TEXT link

Once again, thank you all in advance for your review and kind help I receive on this forum. I'll try to keep my request simple.
Simply put, I have working .js code that allows me to save variables in a webapp. The 'button' is currently a text link to start the save process, but I need to use a certain glyphicon instead of a text link (SAVE PROJECT) and can't figure out how to call this out in the javascript. Also, this would have two states, a disabled button, and an enabled button. Again, it's currently working like a champ using text link.
Here is an example of my code. When setting up the app variables... this link 'button' is disabled.
$(".setup").on("click", function(){
if(!$(this).hasClass("disabled")){
if(W != undefined && H != undefined){
init();
}
var w = parseInt($("#setup").css("width")), h = parseInt($("#setup").css("height")),
t = (height - h) / 2+50, l = (width - w) / 2;
$("#setup").css("top", t + "px");
$("#setup").css("left", l + "px");
$("#setup").css("display", "block");
$("#height").val(redRet.height());
$("#width").val(redRet.width());
$(".load").removeClass("disabled");
$(".save").text("SAVE PROJECT");
$(".save").addClass("disabled");
progressing = true;
}
})
After plotting function, I remove the disabled state so the link 'button' is now active to allow selection to save the content. Meaning, I'd need to change the glyphyicon state as well.
$(".plot").on("click", function(){
if(!$(this).hasClass("disabled")){
$(".load").addClass("disabled");
$(".save").removeClass("disabled");
}
})
var saveString, imageFileName, loginUser, progressing = false;
$(".save").on("click", function(){
if(!$(this).hasClass("disabled") && $(this).text() == "SAVE PROJECT"){
$(".plot").addClass("disabled");
saveString = '{';
saveString += '"setup":{'
saveString += '"width":' + W + ',';
saveString += '"height":' + H + ',';
saveString += '"wRatio":' + wRatio + ',';
saveString += '"hRatio":' + hRatio ;
saveString += '},'
saveString += '"image":{'
saveString += '"name":"' + imageFileName + '",';
saveString += '"width":' + kImage.width() + ',';
saveString += '"height":' + kImage.height() + ',';
saveString += '"x":' + kImage.x() + ',';
saveString += '"y":' + kImage.y() + ',';
saveString += '"scale":' + kImage.scale().x ;
saveString += '},'
saveString += '"redRet":{'
saveString += '"width":' + redRet.width() + ',';
saveString += '"height":' + redRet.height() + ',';
saveString += '"x":' + redRet.x() + ',';
saveString += '"y":' + redRet.y() ;
saveString += '},'
saveString += '"mainGroup":{'
saveString += '"width":' + mainGroup.width() + ',';
saveString += '"height":' + mainGroup.height() + ',';
saveString += '"x":' + mainGroup.x() + ',';
saveString += '"y":' + mainGroup.y() + ',';
saveString += '"scale":' + mainGroup.scale().x ;
saveString += '}'
saveString += '}'
if (saveString) {
$.ajax({
type: "POST",
url: "http://domain.com/tester3/upload/save.php",
data: "user=" + loginUser + "&jsonString=" + saveString,
success: function(html){
$("#message .modal-body").html("<p>"+html+"</p>");
$("#message").modal();
},
error: function(error){
$("#message .modal-body").html("<p>"+error+"</p>");
$("#message").modal();
}
});
}
}
IN SUMMARY: How do I call this out, instead of...
$(".save").text("SAVE PROJECT");
Thank you Billy. The issue I'm having is that the the html uses glyphicons over button types, (transparent bgs) with the class referring to a stylesheet that refers to fonts.
<div class="btnGroup">
<button type="button" class="btn btn-trans setup"><span class="hexioglyph-setup"></span></button>
<button type="button" class="btn btn-trans load disabled"><span class="hexioglyph-load"></span></button>
<button type="button" class="btn btn-trans plot disabled"><span class="hexioglyph-plot"></span></button>
<button type="button" class="btn btn-trans save disabled"><span class="hexioglyph-save"></span></button>
</div>
Which then refers to a stylesheet that links to the fonts.
<link rel="stylesheet" href="hexioglyphs/css/hexioglyphs.css">
Contents of special stylesheet.
.btn-trans {
background: none;
box-shadow: none !important;
border:none !important;
outline: none !important;
active: none !important;
}
#font-face {
font-family: 'hexioglyphs';
src: url('../font/hexioglyphs.eot?4598548');
src: url('../font/hexioglyphs.eot?4598548#iefix') format('embedded-opentype'),
url('../font/hexioglyphs.woff?4598548') format('woff'),
url('../font/hexioglyphs.ttf?4598548') format('truetype'),
url('../font/hexioglyphs.svg?4598548#hexioglyphs') format('svg');
font-weight: normal;
font-style: normal;
}
#media screen and (-webkit-min-device-pixel-ratio:0) {
#font-face {
font-family: 'hexioglyphs';
src: url('../font/hexioglyphs.svg?4598548#hexioglyphs') format('svg');
[class^="hexioglyph-"]:before, [class*=" hexioglyph-"]:before {
font-family: "hexioglyphs";
font-style: normal;
font-weight: normal;
font-size: 3em;
speak: none;
display: inline-block;
text-decoration: inherit;
width: 1em;
margin-right: .2em;
text-align: center;
font-variant: normal;
text-transform: none;
line-height: 2em;
margin-left: .2em;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.hexioglyph-setup { color: #959595;}
.hexioglyph-setup:before { content: '\e801'; }
.hexioglyph-setup:hover { color: #0090ff; }
.hexioglyph-load { color: #959595;}
.hexioglyph-load:before { content: '\e802'; }
.hexioglyph-load:hover { color: #0090ff; }
.hexioglyph-plot { color: #959595;}
.hexioglyph-plot:before { content: '\e803'; }
.hexioglyph-plot:hover { color: #0090ff; }
.hexioglyph-save { color: #959595;}
.hexioglyph-save:before { content: '\e804'; }
.hexioglyph-save:hover { color: #0090ff; }
.glyphicon-folder-open { color: #959595; }
.glyphicon-folder-open:hover { color: #0090ff; }
All the other glyphs show up fine, except the save button.
obviously change the src's to your glyph
var button=document.getElementById('submitButton');
button.onclick=function(){
this.src="http://placehold.it/200x50";
}
<input type="image" src="http://placehold.it/100x50" id="submitButton" alt="Submit">

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
});

Categories

Resources