This jQuery code parse json data and create html table to div:
$(document).ready(function () {
const jsonData = $.getJSON("js/quotes.json");
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function () {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && a.$div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 50e3);
});
}),
this._init();
}
quotes("#quotes-block1", $("#quotes-block1").data("quotes1").split(","));
quotes("#quotes-block2", $("#quotes-block2").data("quotes2").split(","));
});
HTML code:
<div id="quotes-block1" data-quotes1="EUR/USD, GBP/USD, USD/CHF, USD/JPY"></div>
<div id="quotes-block2" data-quotes2="XRP/USD, LTC/USD"></div>
Json:
"XRP\/USD": {
"bid": 0.5676,
"ask": 0.5698,
"type": "Cryptos",
"code": "XRP\/USD",
"mid": 0.5687,
"movement": "down",
"spread": 0.0022
},
"LTC\/USD": {
"bid": 82.89,
"ask": 83.72,
"type": "Cryptos",
"code": "LTC\/USD",
"mid": 83.305,
"movement": "down",
"spread": 0.83
},
"ETH\/USD": {
"bid": 588.62,
"ask": 589.63,
"type": "Cryptos",
"code": "ETH\/USD",
"mid": 589.125,
"movement": "up",
"spread": 1.01
},
etc.
I need create table in div id="quotes-block1" and id="quotes-block2", but work only div id="quotes-block2"
What is my mistake? Help!
Live example:
json file: http://maxbeaub.bget.ru/json/js/quotes.json
jquery function: http://maxbeaub.bget.ru/json/js/quotes.js (get data from json and append table to div)
html result: http://maxbeaub.bget.ru/json/json.html (append table only to second div)
The reason being is content being overwritten in second div only get referenced in an a.
function quotes(a, b) {
(this.$div = $(a)),
(this._quotes = b),
(this._init = function (div) {
var a = this;
jsonData.then(function (b) {
if ("object" != typeof b) return !1;
var c = [];
a._quotes.forEach(function (a) {
(a = a.trim()),
b[a] &&
c.push(
'<tr data-name="' + b[a].code + '" class="' + b[a].movement + '"><td>' +
b[a].code +
'</td><td>' +
b[a].bid +
'</td><td>' +
b[a].ask +
'</td><td>' +
b[a].spread +
"</td></tr>"
);
}),
c.length > 0 && div.html("<table><tr><th>Symbol</th><th>Bid</th><th>Ask</th><th>Spread</th></tr>" + c.join("") + "</table>"),
setTimeout(a._init, 5e3);
});
}),
this._init(this.$div);
Related
I have this script that a fellow here on the site helped me fix.
This is the first part of the code where you can choose and separate blog articles by tag.
Would it be possible to add CSS in this first part of the code where we have the tags Terror, Shounen, Açãoand make each tag a different color?
For example: Terror: blue - Shounen: yellow - Ação: green
This script pulls the blogger content by the tag, but all columns are the same color, I would like to add a css in each to differentiate them.
<div id="feed-list-container"></div>
<div style="clear:both;"></div>
<script type="text/javascript">
var multiFeed = {
feedsUri: [
{
name: "Judul Widget 1",
url: "https://elfenliedbrazil.blogspot.com/",
tag: "Terror"
},
{
name: "Judul Widget 2",
url: "https://elfenliedbrazil.blogspot.com/",
tag: "Shounen"
},
{
name: "Judul Widget 1",
url: "https://elfenliedbrazil.blogspot.com/",
tag: "Ação"
}
],
numPost: 3,
showThumbnail: true,
showSummary: true,
summaryLength: 80,
titleLength: "auto",
thumbSize: 200,
containerId: "feed-list-container",
readMore: {
text: "Selengkapnya",
endParam: "?max-results=20"
}
};
</script>
This is the second part of the code.
<script>
/*<![CDATA[*/
var mf_defaults = {
feedsUri: [{
name: "Posting JQuery",
url: " ",
tag: "JQuery"
}, {
name: "Posting CSS",
url: "",
tag: "CSS"
}, {
name: "Widget-Widget Blogger",
url: " ",
tag: "Widget"
}],
numPost: 4,
showThumbnail: true,
showSummary: true,
summaryLength: 80,
titleLength: "auto",
thumbSize: 200,
thumbWidth: 200, // new setting
thumbHeight: 90, // new setting
newTabLink: false,
containerId: "feed-list-container",
listClass: "list-entries",
readMore: {
text: "More",
endParam: "?max-results=20"
},
autoHeight: false,
current: 0,
onLoadFeed: function(a) {},
onLoadComplete: function() {},
loadFeed: function(c) {
var d = document.getElementsByTagName("head")[0],
a = document.getElementById(this.containerId),
b = document.createElement("script");
b.type = "text/javascript";
b.src = this.feedsUri[c].url + "/feeds/posts/summary" + (this.feedsUri[c].tag ? "/-/" + this.feedsUri[c].tag : "") + "?alt=json-in-script&max-results=" + this.numPost + "&callback=listEntries";
d.appendChild(b)
}
};
for(var i in mf_defaults) {
mf_defaults[i] = (typeof(multiFeed[i]) !== undefined && typeof(multiFeed[i]) !== "undefined") ? multiFeed[i] : mf_defaults[i]
}
function listEntries(q) {
var p = q.feed.entry,
c = mf_defaults,
h = document.getElementById(c.containerId),
a = document.createElement("div"),
d = "",
l = c.feedsUri.length,
n, k, m, g;
for(var f = 0; f < c.numPost; f++) {
if(f == p.length) {
break
}
n = (c.titleLength !== "auto") ? p[f].title.$t.substring(0, c.titleLength) + (c.titleLength < p[f].title.$t.length ? "…" : "") : p[f].title.$t;
m = ("summary" in p[f]) ? p[f].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : "";
m = (c.summaryLength < m.length) ? m.substring(0, c.summaryLength) + "…" : m;
g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;">' : '';
for(var e = 0, b = p[f].link.length; e < b; e++) {
k = (p[f].link[e].rel == "alternate") ? p[f].link[e].href : "#"
}
d += '<div class="post hentry"' + (!c.autoHeight ? ' style="height' + c.thumbHeight + 'px;overflow:hidden;"' : "") + ">";
d += (c.showThumbnail) ? g : "";
d += '<div class="post-title entry-title">" + n + "</div>";
d += '<div class="summary">';
d += "<span" + (!c.showSummary ? ' style="display:none;"' : "") + ">";
d += (c.showSummary) ? m : "";
d += "</span></div>";
d += '<span style="display:block;clear:both;"></span></div>'
}
d += "";
d += '<div class="more-link">" + c.readMore.text + "</div>";
a.className = c.listClass;
a.innerHTML = '<div class="main-title"><h4>' + c.feedsUri[c.current].name + "</h4></div>" + d;
h.appendChild(a);
c.onLoadFeed(c.current);
if((c.current + 1) < l) {
c.loadFeed(c.current + 1)
}
if((c.current + 1) == l) {
c.onLoadComplete()
}
c.current++
}
mf_defaults.loadFeed(0);
/*]]>*/
</script>
Expanding on my comment:
Might be worthwhile to explore using data attributes. Though you could also add a color code attribute to your json, and at a.innerHTML in your javascript section have it do inline css/set the background-color for the div.
It's important to note though, there are likely many solutions to your question, this is just how I'd do it.
Your css file could look something like this:
div[data-tag='Terror'] {
background-color: blue;
}
div[data-tag='Shounen'] {
background-color: yellow;
}
div[data-tag='Ação'] {
background-color: green;
}
and you'd update your javascript to include a data-tag="'+c.feedsUri[c.current].tag+'" on your html element of interest.
The anchor tag may not be where exactly you'd want it, but this would at least get you started in the direction I perceive you're attempting to go.
a.innerHTML = '<div data-tag="'+c.feedsUri[c.current].tag+'" +class="main-title"><h4>' + c.feedsUri[c.current].name + "</h4></div>" + d;
I have a JSON which I query with xhr. The objects (person) contain a key-value pair called "serviceLevel" that I have to split.
When I stack this in a variable (services) and log it like this:
let main = document.getElementsByTagName('main');
getXHR("GET", './db/orga.json', (success) => {
format(success)
}, (error) => {
console.error(error)
});
function format() {
let people = arguments[0];
for (let i in people) {
let person = people[i];
let services = person.serviceLevel.split(".");
console.log(services);
console.log(person.serviceLevel.split("."));
let idCard = document.createElement('div');
idCard.id = person.firstName + person.familyName;
idCard.classList.add('person');
idCard.innerHTML = "<div class=\"item nom\"><span class=\"prenom\">" + person.firstName + "</span><span class=\"famille\">" + person.familyName + "</span></div>";
idCard.innerHTML += "<span class=\"job\">" + person.jobTitle_1 + "</span>";
idCard.innerHTML += "<span class=\"mail\"><a href=\"mailto:" + person.mail + "\">" + person.mail + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.phone_1 + "\">" + person.phone_1 + "</span>";
idCard.innerHTML += "<span class=\"tel\"><a href=\"tel:" + person.mobile + "\">" + person.mobile + "</span>";
for (let j in services) {
let serviceElement = document.getElementById(services[j]);
if (!serviceElement) {
let serviceElement = document.createElement('div');
serviceElement.id = services[j];
serviceElement.classList.add('n' + j, "service");
serviceElement.innerHTML = "<span class=\"title\">" + services[j] + "</span>";
if (j == 0) {
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
main[0].appendChild(serviceElement);
}
} else {
let parent = services[j - 1],
parentService = document.getElementById(parent);
if (services[services.length - 1] = j) {
serviceElement.appendChild(idCard);
}
parentService.appendChild(serviceElement);
}
} else {
serviceElement.appendChild(idCard);
}
}
}
}
const data = [{
"Tri": "blablablabla, CSMSI.SAFS, n, XXXX, YYYY",
"Department": "The best department",
"serviceLevel": "CSMSI.SAFS",
"organisationLevel": "blablablabla",
"rang": "n",
"familyName": "XXXX",
"firstName": "YYYY",
"jobTitle_2": "Directeur",
"jobTitle_1": "Directeur",
"phone_1": "nn nn nn nn nn",
"phone_2": "",
"mobile": "nn nn nn nn nn",
"mail": "xxxx.yyyy#zzzz.fr",
"location": "france"
}];
format(data);
The results are different:
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "SAFS"
length: 2
(2) ["CSMSI", "SAFS"]
0: "CSMSI"
1: "1"
length: 2
As we can see, content of "services" are good, but when I extend the tree, the value of the second key value is "1" ... which is a problem. Is there a way to change this?
when I use a for loop with "classical" (i = 0; i < people.length; i++), i don't have the problem....
Im trying to get value from an array:
[
{
"id": "5899aaa321e01b8b050041cb",
"name": "John Doe",
"picture": {"small": "https://cdn.image.com/1234"},
"age": 28,
"location": {"city": "London"},
"following": 1,
"resources": {"band": "http://image/music"},
"top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {"small": "https://cdn.image.com/1234"}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {"small": "https://cdn.image.com/1234"}
}
}
]
}
]
$(document).ready(function() {
$.ajax({
type: 'GET',
url: '/api/url/123',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, element) {
$('#api').append('<div>'
+ ' <div><h3>' + element.name + '</h3></div>'
+ '<div>' + element.top_works[2].portfolio.picture.small + '></div>');
});
}
});
});
I can read without problem all, neither the "top_works, because i need to specific the number [x], and I need a loop.
In some case if the top_works is empty i get an "undefined in console", i need to show a white space if the element does'nt exsist.
Someone can help me?
You should verify if that exists, something like:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var exists = element.top_works[2] && element.top_works[2].portfolio && element.top_works[2].portfolio.picture && element.top_works[2].portfolio.picture.small;
HTML+= exists ? '<div>' + element.top_works[2].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
But if you want to search for a picture on the last index, maybe you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
var last = element.top_works ? element.top_works.length-1 : -1;
var exists = last >= 0;
HTML+= exists ? '<div>' + element.top_works[last].portfolio.picture.small + '</div>' : '<div>#empty space</div>';
$('#api').append(HTML + '</div>');
});
EDIT
For a loop, you can do this:
$.each(data, function (index, element) {
var HTML = '<div>'
+ ' <div><h3>' + element.name + '</h3></div>';
if(element.top_works && element.top_works.length > 0) {
for(var i in element.top_works) {
HTML+= '<div>' + element.top_works[i].portfolio.picture.small + '</div>';
}
} else {
HTML += '<div>#empty space</div>';
}
$('#api').append(HTML + '</div>');
});
you can make use of array.length property to check if and element exists or not as shown in following example.
var topWorks = { "top_works": [
{
"points": 20,
"portfolio": {
"facebook_id": "1e691681472",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
{
"points": 10,
"portfolio": {
"facebook_id": "1e6916r17ry",
"picture": {
"small": "https://cdn.image.com/1234",
}
}
},
]
}
if(topWorks.top_works.length > 0) {
console.log("Top works has element at index 0");
}
if(topWorks.top_works.length > 1) {
console.log("Top works has element at index 1");
}
if(topWorks.top_works.length > 2) {
console.log("Top works has element at index 2");
}else
{
console.log("Top works does not have element at index 2");
}
I have a ajax returning data some times like
{
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]
}
for above my forEach function is working fine but when same data is returning
{
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}
}
my forEach function not working
$.get(url, function(data){
var x =data['results'];
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
});
});
That's because your JSON isn't an array. You can easily check beforehand using Array.isArray(). You should also be using getJSON if the data you are retrieving is in fact JSON.
$.getJSON(url, function(data) {
var x = data.results;
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
$(self).append('<button class="tag-format" title="' + array[index].Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + array[index].symbol + " - " + array[index].PriceSales + ' </button>');
});
} else {
$(self).append('<button class="tag-format" title="' + x.Name + '" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> ' + x.symbol + " - " + x.PriceSales + ' </button>');
}
});
Your forEach is for iterating over an array. In your second JSON, there is no array to iterate over, so you need to call the function directly on data['results']:
$.get(url, function(data){
var x = data['results'],
addButton = function(item) {
$(self).append('<button class="tag-format" title="'+array[index].Name+'" style="color:#fff;background-color:rgb(0,151,216);border:1px solid;border-radius:10px;"> '+ array[index].symbol +" - "+ array[index].PriceSales +' </button>');
};
if(Array.isArray(x)) {
x.forEach(function logArrayElements(element, index, array) {
addButton(array[index]);
});
} else {
addButton(x);
}
});
Javascript object is not an Array.
Html
<div id="results"></div>
Javascript
var firstArray = {
"results": [{
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}]};
var secondArray = {
"results": {
"symbol": "AppConomy",
"Name": null,
"PriceSales": null
}};
//Result: 1
$("#results").append("<span>FirstArray result: " + firstArray['results'].length + "</span><br/>");
//Result: undefined
$("#results").append("<span>FirstArray result: " + secondArray['results'].length + "</span><br/>");
$ (function() {
var heroes = {
"Abaddon":{
"counters": "Undying" + "Anti-Mage" + "Outworld Devourer" + "Shadow Demon" + "Techies" + "Ancient Apparition" + "Meepo" + "Riki"
},
"Alchemist":{
"counters": "Riki" + "Ursa" + "Drow" + "Phantom Assassin" + "Troll Warlord" + "Bounty Hunter" + "Slark" + "Lifestealer"
},
"Ancient Apparition":{
"counters": "Anti-Mage" + "Clinkz" + "Riki" + "Juggernaut" + "Zeus" + "Techies" + "Phantom Assassin" + "Spectre"
},
"Axe":{
"counters": "Timbersaw" + "Venomancer" + "Silencer" + "Necrophos" + "Zeus" + "Phoenix" + "Lich" + "Ancient Apparition"
},
"Bane":{
"counters": "Phantom Lancer" + "Chaos Knight" + "Meepo" + "Tidehunter" + "Sand King" + "Razor" + "Naga Siren" + "Undying"
},
"Batrider":{
"counters": "Huskar" + "Viper" + "Juggernaut" + "Sniper" + "Venomancer" + "Undying" + "Weaver" + "Drow Ranger"
},
"Beastmaster":{
"counters": "Axe" + "Bristleback" + "Lich" + "Timbersaw" + "Zeus" + "Meepo" + "Centaur Warrunner" + "Tidehunter"
},
"Bloodseeker":{
"counters": "Wraith King" + "Techies" + "Tiny" + "Troll Warlod" + "Lifestealer" + "Dragon Knight" + "Legion Commander" + "Chaos Knight"
},
"Bounty Hunter":{
"counters": "Phantom Lancer" + "Slardar" + "Meepo" + "Naga Siren" + "Bloodseeker" + "Chaos Knight" + "Huskar" + "Techies"
},
"Brewmaster":{
"counters": "Undying" + "Omniknight" + "Death Prophet" + "Timbersaw" + "Weaver" + "Techies" + "Queen of Pain" + "Anti-Mage"
},
"Bristleback":{
"counters": "Necrophos" + "Venomancer" + "Viper" + "Ancient Apparition" + "Razor" + "Death Prophet" + "Clockwerk" + "Omniknight"
},
};
var keys = [];
for(var k in heroes) keys.push(k);
$("#searchBar").autocomplete({
source: keys
});
$( "#searchBar" ).autocomplete({ minLength: 2 });
var minLength = $( "#searchBar" ).autocomplete( "option", "minLength" );
$( "#searchBar" ).autocomplete( "option", "minLength", 2 );
$( "#searchBar" ).autocomplete({ autoFocus: true });
$( "#searchBar" ).autocomplete({response: function( event, ui ) {} });
$("#searchBar").bind("keypress", function(e) {
var key = e.keyCode || e.which;
if(key == 13) {
for (var i = 0; i < heroes.length; i++) {
if (document.getElementById("searchBar").value == heroes);
document.getElementById("placeholder").innerHTML = heroes.counters;
};
}
});
});
So basically what I'm trying to build is a counter hero list. what I want to achieve is that when I put a string into the input field (#searchBar) it will run it through my object and see if it matches, it it matches it will return the value(counters, but it's not working.
You are not iterating object fields correctly.
Also I suggest you to use select event of Autocomplete plugin instead of keypress
Here's working code:
$( "#searchBar" ).autocomplete({select: function( event, ui ) {
for (var hero in heroes) {
if (document.getElementById("searchBar").value == hero) {
document.getElementById("placeholder").innerHTML = heroes[hero].counters;
}
};
} });
http://jsfiddle.net/bo1ce55L/2/