I am doing an exercise related with JSON and JavaScript. However, I just could not figure out that what's wrong with my syntax. It should show the links on the ordered list part in HTML, but I got only H2 tag.
Here is the syntax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Javascript and jason</title>
</head>
<body>
<h2>Links</h2>
<ol id="links">
</ol>
<script>
var info = {
"full_name":"Ray Villaobos",
"title" : "Staff Author",
"links" :[
{"blog":"http://iviewsource.com"},
{"facebook":"http://facebook.com/iviewsource"},
{"youtube":"http://www.youtube.com"},
{"podcast":"http://feeds.feedburer.com/authoredcontent"},
{"twitter":"http://twitter.com/planetoftheweb"}
]
};
var output = '';
for (var i=0; i <=info.links.length; i++) {
for (key in info.links[i]){
if (info.links[i].hasOwnProperty(key))
{
output +='<li>' +
'<a href ="' + info.links[i][key]+
'">' +'</a>' +
'<li>';
}
}
}
var update = document.getElementById('links');
update.innerHtml = output;
</script>
</body>
</html>
You don't see anything because you have a typo. Remember that JavaScript is case-sensitive.
It should be :
update.innerHTML = output;
So with uppercase HTML.
But it might be better to use appendChild like so:
var output = '';
var update = document.getElementById('links');
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', info.links[i][key]);
a.text = key;
li.appendChild(a);
update.appendChild(li);
}
}
}
See Fiddle
Three problems:
You're not closing your li elements; you have another <li> where the closing </li> should be.
You're not putting anything inside the <a> tags. I'm including key as the link text here.
innerHtml should be innerHTML.
var info = {
"full_name": "Ray Villaobos",
"title": "Staff Author",
"links": [{
"blog": "http://iviewsource.com"
}, {
"facebook": "http://facebook.com/iviewsource"
}, {
"youtube": "http://www.youtube.com"
}, {
"podcast": "http://feeds.feedburer.com/authoredcontent"
}, {
"twitter": "http://twitter.com/planetoftheweb"
}]
};
var output = '';
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
output += '<li>' +
'<a href="' + info.links[i][key] +
'">' + key + '</a>' +
'</li>';
}
}
}
var update = document.getElementById('links');
update.innerHTML = output;
<h2>Links</h2>
<ol id="links">
</ol>
Related
I have 3 elements arranged in a row. I want to show a carousel pop-up on click of the columns in the row. The issue is I am not able to change the images of carousal based on selected column element.
Here is my complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 70%;
margin: auto;
}
</style>
</head>
<script>
function process() {
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
for(var i=0; i< shops.length; i++) {
if(row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(shops[i])" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="'+shops[i].link+'" width="100%" height="100%"/></div>';
if(row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
processCarousel();
}
function processCarousel(input) {
alert(input);
var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg'];
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for(var i=0 ; i< m.length ; i++) {
var c = "";
if(i == 0) {
c = " active";
}
innerContent += '<div class="item'+c+'"><img src="'+m[i]+'"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class='+c+'data-target="#carousel-example-generic" data-slide-to="'+i+'"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
carouselExampleGeneric.carousel();
}
</script>
</html>
The above code generates the below output:
On click of any image it is loading the carousal but the images of carousal are fixed to my array elements var m = ['img_chania.jpg','img_chania2.jpg', 'img_flower.jpg','img_flower2.jpg']; as mentioned in my above code.
But I want to show only the selected images which are present in my input json shops.categories[selectedItem].images
I tried using onclick javascript event on column element, but the code is not recognising it. What is the correct way to do this.
I want to do this using plain javascript.
First you need to get rid of the call to processCarousel(); in line 39.
Your main problem is, that inside of your content variable you are passing the string of the argument variable rather than the argument itself. Try this instead:
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
This way you are just passing the index of the category that needs to be rendered.
Then you will have to have the shops object available inside of the processCarousel function as well, so I moved it up, outside the function scope.
This will result in further problems inside of you processCarousel function. You will have to set your your images like this var m = shops[i].images; instead of var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
This will throw another error further down.
innerContent += '<div class="item' + c + '"><img src="' + m[i] + '"><div class="carousel-caption"></div> </div>'; will not work. Instead you will have to use m[i].href as your source inside your image tag.
This will now pass the config to the Carousel which will then render just fine.
You might want to think about giving variables speaking names and avoiding variables like 'm'.
var shops = JSON.parse('{ "id": "shopping", "categories": [ { "id": "Amazon", "name": "Amazon", "link": "https://images-na.ssl-images-amazon.com/images/G/01/SellerCentral/legal/amazon-logo_transparent._CB303899249_.png", "images": [ { "href": "https://images-na.ssl-images-amazon.com/images/G/01/credit/img16/CBCC/marketing/marketingpage/products._V524365396_.png" }, { "href": "http://static4.uk.businessinsider.com/image/575adbe2dd0895c4098b46ba/the-50-most-popular-products-on-amazon.jpg" } ] }, { "id": "Google", "name": "Google", "link": "http://pngimg.com/uploads/google/google_PNG19644.png", "images": [ { "href": "https://www.clipartmax.com/png/middle/147-1476512_google-google-products-logos-png.png" }, { "href": "https://xvp.akamaized.net/assets/illustrations/unblock-google/unblock-google-with-a-vpn-fc1e32f59d9c50bae315c2c8506a91e2.png" } ] }, { "id": "Apple", "name": "Apple", "link": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Apple_Logo.svg/2000px-Apple_Logo.svg.png", "images": [ { "href": "https://c.slashgear.com/wp-content/uploads/2018/03/apple-mfi-logos-update-2018-980x620.jpg" }, { "href": "https://support.apple.com/library/content/dam/edam/applecare/images/en_US/applemusic/itunes-apple-logo-apple-music-giftcard.jpg" } ] } ] }');
var row = 1;
var content = "";
shops = shops.categories;
function process() {
for (var i = 0; i < shops.length; i++) {
if (row == 1) {
content += '<div class="row">'
}
content += '<div class="col-md-4 col-sm-12" data-toggle="modal" onclick="processCarousel(' + i + ')" data-target="#myModal">';
content += '<img style="border: 1px solid red" src="' + shops[i].link + '" width="100%" height="100%"/></div>';
if (row == 3) {
row = 0;
content += '</div>';
}
row++;
}
document.getElementById("placeholder").innerHTML = content;
}
function processCarousel(i) {
//var m = ['img_chania.jpg', 'img_chania2.jpg', 'img_flower.jpg', 'img_flower2.jpg'];
var m = shops[i].images;
var carouselInner = document.getElementById("carousel-inner");
var carouselIndicators = document.getElementById("carousel-indicators");
var innerContent = "";
var indicatorsContent = "";
for (var i = 0; i < m.length; i++) {
var c = "";
if (i == 0) {
c = " active";
}
innerContent += '<div class="item' + c + '"><img src="' + m[i].href + '"><div class="carousel-caption"></div> </div>';
indicatorsContent += '<li class=' + c + 'data-target="#carousel-example-generic" data-slide-to="' + i + '"></li>';
}
carouselInner.innerHTML = innerContent;
carouselIndicators.innerHTML = indicatorsContent;
var carouselExampleGeneric = document.getElementById("carousel-example-generic");
//carouselExampleGeneric.carousel();
}
I have this for loop
<script>
...
for(i = 0;i < json.length;i++){
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
</script>
I want to print a paragraph with a href on each loop, so i did this:
</script>
<a id="pLink">
<p id="pText">
</p>
</a>
It works but the thing is this only prints the last loop.
So i tried this inside the script
document.write("<a href=\"" + json[i].html_url + "\">");
document.write("<p>" + json[i].name + "</p>");
document.write("</a>");
instead of this:
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
And it prints everything i want but it replaces the whole page.
How can i do this? Do i need to create an id for every loop? Like "pText1, pText2, etc.
Create a container element for that loop, and add the html as you had in mind
<div id="container"></div>
Then in javascript
var container = document.getElementById('container');
var my_html = '';
for(var i = 0;i < json.length;i++){
my_html += '<a href="' + json[i].html_url + '\">';
my_html += '<p>'+ json[i].name + '</p>'
my_html += '</a>'
}
container.innerHTML = my_html;
What we are doing here is adding the content to a string as many times as needed and then add it to the container so it already has all the loops
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
If you want to use your this code, you have to write "+=" instead of the "=".
var json = [
{"name":"Name 1", "html_url": "http://www.example.com"},
{"name":"Name 2", "html_url": "http://www.example.com"},
{"name":"Name 3", "html_url": "http://www.example.com"}
];
for(var i = 0; i < json.length; i++){
document.getElementById("pText").innerHTML += json[i].name + "<br>";
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
<a id="pLink">
<p id="pText">
</p>
</a>
I will do it in the following way:
let json = [{'name':'Google','html_url':'https://www.google.com/'}, {'name':'Facebook','html_url':'https://www.facebook.com/'}, {'name':'Twitter','html_url':'https://twitter.com/?lang=en'}];
let item = document.querySelector(".pLink")
for(let j = 1; j<json.length; j++){
let cln = item.cloneNode(true);
document.body.appendChild(cln);
}
let aTag = document.querySelectorAll('a.pLink');
aTag.forEach(function(item, i){
let a = item.setAttribute("href",json[i].html_url);
let p = item.querySelector('.pText');
p.innerHTML = json[i].name;
})
<a class="pLink">
<p class="pText">
</p>
</a>
I got an array from json and I need to put each item in a <li> on my html
something like this :
names : {john, paul, ringo,george}
into <li>john</li>..
my code:
<div id="demo"></div>
script:
function onLocationsReceived(data) {
console.log("recievd");
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
document.getElementById("demo").innerHTML = sensorNames;
console.log(sensorNames);
}
}
on the concole.log it prints just fine..
document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>
something like that???
Using something like below
function onLocationsReceived(data){
var html="";
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
html+="<li>"+sensorNames+"</li>";
console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}
You can use syntax below
document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'
You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:
var content = "",
sensorNames;
for (var i = 0; i < data[0].Sensors.length; i++) {
sensorNames = data[0].Sensors[i].Name;
content += "<li>" + sensorNames + "</li>";
}
document.getElementById("demo").innerHTML = content;
I have this problem where my words of JSON won't load into my Webpage, the images do work already, fortunally..
I already have the images that needed to be loaded trough JSON into my Webpage.
I still need some words to load trough JSON into my Webpage,
{"main_object": {
"imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
"wordsJ": ["næb", "kat", "æg", "mel", "mælk", "pas", "ske", "te"]
}
}
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
header {
height: 5%;
}
body {
background-color: #f0f0f0;
}
.container {
height: 90%;
}
.images img {
height: 100px;
width: 100px;
}
footer{
height: 5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sleepopdracht</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/css.css">
</head>
<body>
<header>
</header>
<div class="container" id="container"><div class="images" id="images"></div>
<div class="words" id="words"></div>
</div>
<footer>
</footer>
<script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>
In the Javascript you can see that I loaded the words a little like the images, as far as I know it should just work, but the console reports an
Uncaught ReferenceError: Invalid left-hand side in assignment ~ jquery.min.js:4
I can't seem to figure out te source of the problem, neighter do I know how to solve it full.
It seems that The error exists even if i commend the Words loop out, The Error existed already without the code calling the words JSON. But now the problem still is that I can't find the source of the problem, if I found it, it is probably easy to solve. Since the last time I checked, the code ran perfectly without the Words Loop
I see that you havn't defined imagesJ and wordsJ
var imagesJ;
var wordsj;
And you need to do something like this
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
Final File
var jsonData = "noJson";
var hr = new XMLHttpRequest();
var imagesJ;
var wordsj;
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Try changing this code:
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
to:
var words = document.getElementById('words')
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
I found that the problem was in
document.getElementById('images') = html;
this was wrong, first I didn't call html at all so I made a var after console log of html with an empty string.
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
The var html2 is for the words.
then my document.getElementById was not complete (that was the Error)
This was the proper code for the document.
document.getElementById('images').innerHTML = html;
Then I had,
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
wich needed to be this,
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
So my full code then was,
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
for(i = 0; i < imagesJ.length; i++) {
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
//images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images').innerHTML = html;
//$('#images').append(html);
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>'+wordsJ[i]+'</span>';
}
document.getElementById('words').innerHTML = html2;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Altough I still don't have the words in my browser, the Error is resolved.
Thanks Everyone :D Happy programming!
I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.
#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>