Js: show JSON data in HTML - javascript

below i have JSON data for cafe menu and i want to view them in HTMl page as grid view showing image, name and price ... is there a way to do this in JS and HTML?
[
{
"placeImage": "assets/images/straw-1.jpg",
"placeName": " pizza",
"price": 15000
},
{
"placeImage": "assets/images/straw-1.jpg",
"placeName": " Burger",
"price": 15000
},
]

This partly depends on if you're processing that data on the server side or the client side. Either way, you can access the JSON data in your JS script like this:
const cafeData = require('./cafe.json'); // If it is in the same directory as the script
console.log(cafeData);
If you're trying to create a dynamic HTML page with data from a server, then try using a templating language like EJS, which is the simplest to learn for a JavaScript developer. If you're on the client side then you'll need to use the DOM to insert that data into your HTML. For example, if you have an element in a product card like this: <div id="pizzaPriceDisplay">
Then you're JS code might look something like this:
const priceDisplay = document.querySelector('#pizzaPriceDisplay');
pizzaPriceDisplay.innerText = '$' + cafeData[0].price;
Hope I helped and happy coding :)

Sure! Lets asume that your JSON data is stored in a javascript string
const jsonData = "..."; //The JSON string
The first thing to do would be to turn that json data into a javascript object that we can iterate. We can do that like this:
const data = JSON.parse(jsonData);
Cool, now, as far as i can tell you want to turn every item into an HTML element (like a card) and display all of them in a grid. The grid part can be pretty trivial now days using CSS Grid: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout.
So somewhere in your HTML you would want to have an element like this:
...
<div class="grid-container" id="menu-items-container">
<!-- We are going to insert your rendered data here -->
</div>
...
And somewhere in your css you will have something like this
...
.grid-container{
display:grid;
/* ... */
}
...
Now for the fun part. Taking your the contents of that data variable and turning them into html
//This function will take the data of one item
//And return an html element
function renderItem(item){
const base = document.createElement("div");
const img = document.createElement("img");
const title = document.createElement("h1");
const price = document.createElement("h2");
img.src = item.placeImage;
title.textContent = item.placeName;
price.textContent = item.price;
base.appendChild(img);
base.appendChild(title);
base.appendChild(price);
return base;
}
const container = document.querySelector("#menu-items-container");
for (let item of data){
container.appendChild(renderItem(item));
}
And that's about it, you'll probably want to style the inserted elements a little better, which you can do adding a few classes here and there. But you probably get the gist of it.
For the particular data you gave in the example this should produce something similar to this:
<div class="grid-container" id="menu-items-container">
<div>
<img src="assets/images/straw-1.jpg"/>
<h1>pizza</h1>
<h2>15000</h2>
</div>
<div>
<img src="assets/images/straw-1.jpg"/>
<h1>Burger</h1>
<h2>15000</h2>
</div>
</div>

Simply parse the JSON to JS object
let menu = JSON.parse('[{"placeImage": "assets/images/straw-1.jpg", "placeName": "Pizza", "price": 15000},{"placeImage": "assets/images/straw-1.jpg", "placeName": "Burger","price": 15000}]');
Then you can iterate over it using a loop and draw the HTML you want ex: Table
function drawMenu(menu) {
let tableElement = document.createElement("table");
// Draw the headers of the table
let headerTableRowElement = document.createElement("tr");
let imageHeaderElement = document.createElement("th");
imageHeaderElement.innerText = "Image";
headerTableRowElement.appendChild(imageHeaderElement);
let nameHeaderElement = document.createElement("th");
nameHeaderElement.innerText = "Name";
headerTableRowElement.appendChild(nameHeaderElement);
let priceHeaderElement = document.createElement("th");
priceHeaderElement.innerText = "Price";
headerTableRowElement.appendChild(priceHeaderElement);
tableElement.app.appendChild(headerTableRowElement);
// Draw the items in the menu
for (let i = 0; i < menu.length; ++i) {
let item = menu[i];
let menuItemTableRowElement = document.createElement("tr");
let imageElement = document.createElement("td");
let image = document.createElement("img");
image.setAttribute("src", item.placeImage);
imageElement.appendChild(image);
menuItemTableRowElement.appendChild(imageElement);
let nameElement = document.createElement("td");
nameElement.innerHTML = item.placeName;
menuItemTableRowElement.appendChild(nameElement);
let priceElement = document.createElement("td");
priceElement.innerHTML = item.price;
menuItemTableRowElement.appendChild(priceElement);
tableElement.appendChild(menuItemTableRowElement);
}
document.appendChild(tableElement);
}

Related

Appending multiple templates to a DOM

Java Script
const cardDropdownTemplate = document.querySelector('[Card-Dropdown-Template]');
const cardDropdownContainer = document.querySelector('[card-dropdown-container]');
SearchBoxMainNav.addEventListener('input', async(event) =>{
var input = document.getElementById('SearchTerm').value;
const card = cardDropdownTemplate.content.cloneNode(true).children[0];
cardDropdownContainer.innerHTML = "";
if (input != "") {
var result = cardSearch(input);
console.log(result);
for (var i = 3; i > -1; i--) {
const name = card.querySelector("[Ygo-Card-Name]");
const desc = card.querySelector("[Ygo-Card-Desc]");
name.textContent = result[i].name;
desc.textContent = result[i].desc;
cardDropdownContainer.append(card);
}
console.log(card);
console.log(result);
}
})
Html
<div class="dropdown-Content" card-dropdown-container ></div>
<template Card-Dropdown-Template>
<div class="card-dropdown">
<div class="card-name" Ygo-Card-Name></div>
<div class="card-description" Ygo-Card-Desc></div>
</div>
</template>
So I have this code, when it executes it listens for an input then sends that input into my api searcher, it searches the api for the 4 most simmilar listings in name then Uses a dom template to create a box and puts all the information in it so i can make a Dropdown.
My problem is currently it is only creating one Box and is just overwriting the information in that one box instead of making multiple boxes. Am I just using append wrong or what? When i watch it in slow mo The data gets overwriitten even before the append is reached in the code, so maybe its just drawing the template in real time after the append and the append only makes a new box that first time then does nothing the rest of the times?

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

Get value from a JSON file with multi dimensional array using jQuery $.getJSON method

I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo

Printing an Ordered List from a JS file

I have a js file with the following array
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
In my HTML file I want to create a container and write an ordered list containing all the fruits in the array to the container I just created, however I'm having serious trouble and I can't find much online help. I'm a beginner, this is what I have
<div class = "container1">
</div>
<h3>Fruits</h3>
<html>
<head>
<script src="Web Programming/Assignments/Assignment #3/assignment3/list.js"></script>
</head>
<body>
<div container1= "fruits"></div>
</body>
You should give the element an id, your custom html attribute would work as a selector, but the typical way would be the id. Then you can simple create some elements in a loop, giving them the element's text content:
var fruits = [ "Apples","Oranges","Pears","Grapes","Pineapples","Mangos" ];
var el = document.getElementById('fruits');
var ol = document.createElement('ol');
el.appendChild(ol);
fruits.forEach(function (fruit) {
var f = document.createElement('li');
f.appendChild(document.createTextNode(fruit));
ol.appendChild(f);
});
<div id="fruits"></div>
Just in case you insist on the container1=... you can select that with
var el = document.querySelector('div[container1="fruits"]');
Firstly include your script in your html file. At the bottom of the body.
Give your container id of container or as you like.
And code will be something like this:
var arrayFruits = ["bananas", "apples", "etc"];
var container = document.getElementById("container");
for (var i = 0; i < arrayFruits.length; i++) {
var list = document.createElement("li");
list.innerHTML = arrayFruits[i];
container.appendChild(list);
}

What is the best way to create a list of text and images, using JavaScript and little to no HTML?

So I have successfully made a list using strictly HTML and CSS and that was simple enough. Now, I want to create the same list, while using JavaScript, for the most part. I'm not so sure why its so confusing for me.
Now I understand that in my HTML file, I must create a div for that list, and can implement the content in my .js file, while styling it however in my .css file. So here's what I have (and what I'm assuming is all I need) in my html file:
<div class="container">
<div class="row" id="content-list"></div>
</div>
I haven't really touched my css file yet because I like to save the styling for last.
I have a bit of a starting point in my .js file but let me explain a few things before showing my meaningless code (which I wrote based off what I was trying to understand from other examples or tutorials, but didn't fully know what I was doing). All I want, is to display a list of my favorite movies, along with an image aligned next to each movie title. That's all! I don't plan on adding any elements later, or removing... I just want my list but I can't figure it out! I feel so dumb.
Anyway, here's what I have (and yes I'm including the part I had commented out because I'm not sure which way is better, and I apologize for not finishing what I started with):
// JavaScript Document
function myMovies (movieTitle, movieThumb) {
this.movieTitle = movieTitle;
this.movieThumb = movieThumb;
}
/**
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
**/
myMovies.prototype.myMovies = function (list) {
var html =
};
Please help me, I'm so lost. And if you could also please comment any code you give me, that would be so appreciated. Thank you!
Well, you can do this:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var htmlStr = ''; // declare a variable which will hold the html for list
for(var i=0;i<contentList.length;i++) // create a loop to loop through contentList
{
htmlStr += "<div><img src='"+contentList[i].img_src+"'/>"+contentList[i].content_title+"</div>";
}
document.getElementById('content-list').innerHTML = htmlStr; // assign the innerhtml
I've commented the code.
LIVE DEMO
By the look of that var html =, I take it you're planning to build up a string of HTML code? I'm gonna assume you have your own plans on how to do that. It's mostly string concatenation, after all.
After you have html ready, use document.getElementById to get a reference to the container and set its innerHTML property to the string you've constructed.
document.getElementById('content-list').innerHTML = html;
In Javascript:
var contentList = [
{'content_title':'District 9', 'img_src':'district9.jpg', 'target_dir':''},
{'content_title':'Gladiator', 'img_src':'gladiator.jpg', 'target_dir':''},
{'content_title':'Django Unchained', 'img_src':'django.jpg', 'target_dir':''},
{'content_title':'Fantastic Mr. Fox', 'img_src':'fox.jpg', 'target_dir':''},
{'content_title':'Master and Commander', 'img_src':'master.jpg', 'target_dir':''}
];
var myList = document.createElement("ul"); // create the list
for (var i = 0; i < contentList.length; i++) { // for each Object in your Array
var myItem = document.createElement("li"); // create a item for the list
var myAnchor = document.createElement("a"); // create an anchor for the target_dir property
myAnchor.setAttribute("href", contentList[i].target_dir); // set the href attribute for the anchor
var myTitle = document.createTextNode(contentList[i].content_title); // create the text node to be inside the anchor (from the content_title property)
myAnchor.appendChild(myTitle); // append the text into the anchor
var myImage = document.createElement("img"); // create the DOMElement for the image
myImage.setAttribute("src", contentList[i].img_src); // set the attribute src (from the img_src property)
myImage.setAttribute("alt", contentList[i].content_title); // set the alt attribute only cause it's required for both XHTML and HTML5
myItem.appendChild(myAnchor); // append the anchor into the item list
myItem.appendChild(myImage); // append the image into the item list
myList.appendChild(myItem); // append the item list into the list
}
document.getElementById("content-list").appendChild(myList); // append the list into the div you've created
In jQuery:
var myList = $("<ul>")
for (var i = 0; i < contentList.length; i++) {
var myItem = $("<li>");
var myAnchor = $("<a>").attr("href", contentList[i].target_dir).text(contentList[i].content_title);
var myImage = $("<img>").attr("src", contentList[i].img_src).attr("alt", contentList[i].content_title);
myItem.append(myAnchor).append(myImage);
myList.append(myItem);
}
$("#content-list").append(myList);
In "ugly" (String concatanation) Javascript:
var myHTML = "<ul>";
for (var i = 0; i < contentList.length; i++) {
myHTML += "<li><a href='" + contentList[i].target_dir + "'>" + contentList[i].content_title + "</a><img src='" + contentList[i].img_src + "' alt='" + contentList[i].content_title + "' /></li>";
}
myHTML += "</ul>"
document.getElementById("content-list").innerHTML = myHTML;

Categories