javascript table alignment - javascript

I'm trying to align the tables' titles with the items form another page using a js loop, tried padding, spacing etc.. nothing worked!
$(document).ready(function() {
let products = ['bread', 'sweets', 'coffee'];
$('#prepurchased').html('<table class ="thead"id="items" ><tr><th>Item</th><th> </th><th>Price</th><th>quantity</th></tr>');
products.forEach(function(i) {
let p = sessionStorage.getItem(i);
if (p !== null) {
p = JSON.parse(p);
$('#prepurchased').append('<table id="items" class="cart" align="center"><tr><td>' + i + '</td>' + '<td>$' + p.price + '</td>' + '<td>' + p.quantity + '</td></tr>');
$('#purchase').css('display', 'block');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>

All your data should be in the same <table>. That's what tables are for. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table
Also:
It seems you wanted to separate <thead> and <tbody>
I removed an empty <th> that was confusing
You made your "purchase" button visible at each data row, which doesn't seem useful
if (p !== null) doesn't prevent rendering the JSON when p is undefined. Just write if (p) instead
$(document).ready(...) is longer to write. You may use the shorthand $(...)
I had to fake sessionStorage for the snippet to run live.
$(_e => {
const products = ['bread', 'sweets', 'coffee'];
$('#prepurchased').html('<table class="cart" id="items"><thead><tr><th>Item</th><th>Price</th><th>quantity</th></tr></thead><tbody></tbody></table>');
products.forEach(i => {
//let p = sessionStorage.getItem(i); //TODO: restore this
let p = fakeStorage[i]; //TODO: remove this
if (p) {
p = JSON.parse(p);
$('#prepurchased .cart tbody').append('<tr><td>' + i + '</td>' + '<td>$' + p.price + '</td>' + '<td>' + p.quantity + '</td></tr>');
}
});
if (products.length)
$('#purchase').css('display', 'block');
});
//TODO: remove, for testing only (sessionStorage rises error with cross-domain js)
fakeStorage = {
'bread': '{"price": 21.2, "quantity": 25}',
'coffee': '{"price": 34.55, "quantity": 32}',
/*'sweets': '{"price": 6.12, "quantity": 1}',*/
};
body {
text-align: center;
}
.cart {
text-align: center;
}
.cart th {
width: 15em;
}
.buttons {
margin-top: 2rem;
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>
<div id="prepurchased"></div>
<div class="buttons">
<button id="purchase" style="display: none">Purchase</button>
</div>

Related

html onclick not happening when parameter has special characters like $ or [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a code in which I have three rows with three parameters $COKE, COKE, COKE.
Every row has a sublist which opens when I click the parameters. It works fine when parameter doesnt have any special characters i.e.
For case when $COKE is parameter it doesn't open sublist onclick. ($ dollar sign)
For case when COKE is parameter it opens sublist onclick.
For case when COKE. is parameter it doesn't open sublist onclick. (. dot sign)
data[i].parameter="$COKE"
document.getElementById("results").innerHTML += "<tr id="+data[i].parameter+" onclick='showSublist(this.id)'>
data[i].paramater can have values as shown below $COKE, COKE.,COKE as an example.
Image shown as reference, where only case 2 opens but case 1 and case 3 doesn't open when I click them.
Cases Image
By not escaping special characters you are creating invalid HTML code, that's why onclick doesn't work.
Here is example how browser handles special characters:
function escape(a) {
return "&#" + a.charCodeAt(0) + ";";
}
function escapeText(text) {
return text.replace(/["'&<>]/g, escape);
}
function showSublist(id) {
alert(id);
}
var data = [{
parameter: "test"
},
{
parameter: "$test"
},
{
parameter: "<test"
},
{
parameter: "test>"
},
{
parameter: "<test>"
},
{
parameter: '"test'
},
{
parameter: 'test"'
},
{
parameter: '"test"'
},
{
parameter: "test."
},
{
parameter: '&test'
},
{
parameter: '&test;'
},
{
parameter: "test${test}"
},
];
for (let i = 0, tr = document.createElement("tr"); i < data.length; i++) {
tr = tr.cloneNode(false);
tr.innerHTML = '<td class="n">' + i + '</td>';
/* original, incorrect structure */
tr.innerHTML += "<td id=" + data[i].parameter + " onclick='showSublist(this.id)'>" + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, no filter */
tr.innerHTML += '<td id="' + data[i].parameter + '" onclick="showSublist(this.id)">' + data[i].parameter + '</td>';
tr.innerHTML += '<td class="n">' + i + '</td>';
/* correct structure, filter */
tr.innerHTML += '<td id="' + escapeText(data[i].parameter) + '" onclick="showSublist(this.id)">' + escapeText(data[i].parameter) + '</td>';
tr.onmouseover = mouseOver;
document.getElementById("results").appendChild(tr);
};
var div = document.getElementById("html");
function mouseOver(e) {
html.textContent = e.target.className == "n" ? e.target.nextSibling.outerHTML : e.target.outerHTML;
}
th {
text-align: start;
}
td:nth-child(even) {
border-right: 1em solid transparent;
}
td:hover {
background-color: rgba(0, 0, 0, 0.1);
cursor: pointer;
}
div {
background-color: white;
color: black;
position: fixed;
bottom: 0;
margin-top: 1em;
padding: 0.5em;
border: 1px solid black;
}
table {
margin-bottom: 3em;
}
<table id="results">
<tr>
<th colspan="2">
Original, no quotes
</th>
<th colspan="2">
Unescaped
</th>
<th colspan="2">
Escaped
</th>
</tr>
</table>
<div id="html"></div>

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.

Add value to parseInt object not working

Here is my javascript:
$('#vendorid').change(function(){
var vendno = $(this).val();
var data_String;
var numpo = parseInt($('#numvendpo').val());
data_String = 'vendorid='+vendno;
$.post('ft-vendno.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val($('#vendponum').val() + data +'-'+ numpo+1);
});
});
My output is:
As seen in the bottom textbox the last number "-31" should be "-4" (3+1). Whereas it is currently adding it as a string. I can't seem to figure out the problem though.
The top textbox is #numvendpo and the bottom is #vendponum forgive me for my confusing variable names.
When you do:
some_string + numpo + 1
As the first value is a string, you are concatenating values from right to left, so you would first concatenate numpo (converting it to string) to some_string, and then 1, also as a string.
You can fix that making sure the operations are done in the right order, so one option might be to add parenthesis around numpo + 1:
$('#vendponum').val($('#vendponum').val() + data + '-' + (numpo + 1));
You can also do the sum before:
var numpo = parseInt($('#numvendpo').val()) + 1;
Or use template strings:
$('#vendponum').val(`${ $('#vendponum').val() }${ data }-${ numpo + 1 }`);
Here you can see what works and what does not:
const $vendorid = $('#vendorid');
const $numvendpo = $('#numvendpo');
const $outputParenthesis = $('#outputParenthesis');
const $outputBefore = $('#outputBefore');
const $outputTemplate = $('#outputTemplate');
const $outputWrong = $('#outputWrong');
$('#vendorid, #numvendpo').on('input', () => {
const vendno = $vendorid.val();
const numpo = parseInt($numvendpo.val());
if (isNaN(numpo)) {
return;
}
const numpoPlusOne = numpo + 1;
$outputParenthesis.text(vendno + '-' + (numpo + 1));
$outputBefore.text(vendno + '-' + numpoPlusOne);
$outputTemplate.text(`${ vendno }-${ numpo + 1 }`);
$outputWrong.text(vendno + '-' + numpo + 1);
});
body,
input {
font-family: monospace;
}
input {
border: 3px solid black;
padding: 8px;
width: 200px;
}
p {
margin: 8px 0;
}
.label {
display: inline-block;
width: 222px;
text-align: right;
margin-right: 8px;
}
.wrong {
color: red;
}
<input placeholder="Vendor ID" id="vendorid" type="text" />
<input placeholder="Num Vendor PO" id="numvendpo" type="text" />
<p><span class="label">WITH PARENTHESIS: </span><span id="outputParenthesis"></span></p>
<p><span class="label">SUM BEFORE: </span><span id="outputBefore"></span></p>
<p><span class="label">TEMPLATE LITERAL: </span><span id="outputTemplate"></span></p>
<p class="wrong"><span class="label">WRONG: </span><span id="outputWrong"></span></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to print the array values in html dom using java script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have created a bus seat layout dynamically ....
and i have selected seats are pushed to array...
and how to print the array values in html DOM.....
below is my html code
<div>
<h2> Choose seats by clicking the corresponding seat in the layout below:</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
below is my css
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
verticle-align:middle;
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
}
below is my js
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
// Add already reserved seats
localStorage.setItem('SeatNum', JSON.stringify(reservedSeat));
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
var selectedSeat = JSON.parse(localStorage.getItem('SeatNum'));
if($(this).hasClass(settings.selectingSeatCss)){
// Add seat in local storage
selectedSeat.push(parseInt($(this).find('a').text()));
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
else{
// Remove seat from local storage
selectedSeat.splice(selectedSeat.indexOf(parseInt($(this).find('a').text())), 1);
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
}
// Logging
console.log('Reserved and selecting seats : ' + JSON.parse(localStorage.getItem('SeatNum')));
});
$('#btnShow').click(function myFunction() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
how to print the array values in html DOM....
i put an alert..
i tried code but that does't work..
i created bus seat layout dynamically i am putting an alert to show the selected seats and all seats but i want to print the selected seat in html Dom....
Take a div in the end of your html
and then put that line where you set the alert
$('#showSit').text(JSON.parse(localStorage.getItem('SeatNum')));

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>

Categories

Resources