Alert value in loop [Javascript] - javascript

I have a page in which I want to put a Name, Image URL, Description in alert and display this info in a loop. But it's not working for me!
Here is the code
let nameArr = [companyName];
let logoArr = [companyLogo];
let logoImgList = [];
let companyList = "";
let aboutCompanyArr = [aboutCompany];
for(let i=0; i < logoArr.length; i++){
logoImgList[i] = "<img src='" + logoArr[i] + "' width=150 height=150>"; //you don't need to add directory here, Image URLs should be direct!
}
for(let i=0; i < nameArr.length; i++){
companyList += "<div class='companyList'>" + logoImgList[i] + "<br>" + nameArr[i] + "<br>" + aboutCompanyArr[i] + "</div>";
}
document.getElementById("companyList").innerHTML = companyList;

var nameArr=[];
var logoArr=[];
var aboutCompanyArr=[];
function addCompany(){
let companyName = prompt("Enter the company name:");
let companyLogo = prompt("Copy and paste URL company logo:");
let aboutCompany = prompt("Say a little about the company:");
nameArr.push(companyName);
logoArr.push(companyLogo);
aboutCompanyArr.push(aboutCompany);
let logoImgList = [];
let companyList = "";
//let companyImgList = [];
for(let i=0; i < logoArr.length; i++){
logoImgList[i] = "<img src='" + logoArr[i] + "' width=150 height=150/>"; //you don't need to add directory here, Image URLs should be direct!
}
for(let i=0; i < nameArr.length; i++){
companyList += "<div class='companyList'>" + logoImgList[i] + "<br>" + nameArr[i] + "<br/>" + aboutCompanyArr[i] + "</div>";
}
document.getElementById("companyList").innerHTML = companyList;
}
Check this.
I've updated the code.

Related

Javascript how to define an object by array of objects

I recently started learning html/javascript and I want a temporary object to be filled with one of the objects from an array based on the current page number.
loadnextpage();
function loadnextpage() {
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' + curpage.title);
}
But when I try to run the code it keeps giving me an error message that curpage is undefined, after that it keeps running and thus the last line of code gives an error, when I ask for curpage.pageNumber. After that it stops running the code.
image clipping of my code with error message
What am I doing wrong?
edit:
here is the entire code:
var pagenumber = 0;
var receipt = [];
var price = 0;
var text = '{"page": [{"pageNumber": "1","title": "kies je formaat","optionName": "size","option": [{"text": "klein","value": "small","extraPrice": "100"},{"text": "middel","value": "medium","extraPrice": "200"},{"text": "groot","value": "large","extraPrice": "300"}]},{"pageNumber": "2","title": "kies je kleur","optionName": "colour","option": [{"text": "rood","value": "red","extraPrice": "10"},{"text": "groen","value": "green","extraPrice": "20"},{"text": "blauw","value": "blue","extraPrice": "30"}]}]}';
var allcontent = [];
allcontent = JSON.parse(text);
var imgpath = 'img/';
loadnextpage();
function loadnextpage(){
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' +
curpage.title);
var radiobuttons = '';
var radiobuttonid = [];
for(var i = 0; i < curpage.option.length; i++) {
var curradio = curpage.option[i];
radiobuttons += '<label><div class="selection-wrap">';
radiobuttons += curradio.text;
radiobuttons += ' <input type="radio" name="';
radiobuttons += curpage.optoinName;
radiobuttons += '" value="';
radiobuttons += curradio.value;
radiobuttons += '" id="';
radiobuttons += curpage.optoinName;
radiobuttons += '_';
radiobuttons += curradio.value;
radiobuttons += '"></div></label></br>';
radiobuttonid.push(curpage.optoinName + '_' + curradio.value)
}
changeDiv('choices', radiobuttons);
for(var i = 0; i < radiobuttonid.length; i++){
document.getElementById(radiobuttonid[i]).onclick = function(){
receipt[pagenumber-1] = curpage.option[i];
for(var i = 0; i < receipt.length; i++){
price += receipt[i].extraPrice;
}
changeImg('previewimg', imgpath + curpage.option[i].value +
'/preview.jpg');
changeDiv('previewprice', '<h1>€' + price + ',-</h1>');
};
}
};
function changeDiv(id, content) {
document.getElementById(id).innerHTML = content;
};
function changeImg(id, img){
document.getElementById(id).src = img;
};

Working with / and variables in object names (JSON) [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 5 years ago.
I'm working with JSON to query the API provided by themoviedb.org.
I want to make a list of episodes. To do so I need to access the length property of several objects named "season/1", "season/2", "season/3" etc., but I get errors all the time.
The returned JSON Code looks as follows:
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"air_date": "2011-04-17",
"episodes": [
{
"air_date": "2011-04-17",
"crew": [],
"episode_number": 1,
"guest_stars": [],
"name": "Der Winter naht",
"overview": "Ein Deserteur der Nachtwache bringt erschreckende Nachrichten von den Ländern nördlich der Mauer, und Lord Eddard \"Ned\" Stark soll die Hand des Königs Robert Baratheon werden.",
"id": 63056,
"production_code": "101",
"season_number": 1,
"still_path": "/wrGWeW4WKxnaeA8sxJb2T9O6ryo.jpg",
"vote_average": 7.493,
"vote_count": 67
},
{...},
.
.
.
]
}
My Javascript code:
var urlBase = 'https://api.themoviedb.org/3/tv/';
var tvId = 'XXX';
var apiKey = '?api_key=MYKEY';
var apiLang = '&language=de_DE';
var descElement = document.getElementById('description');
var titleElement = document.getElementById('title');
var posterElement = document.getElementById('poster');
var castElement = document.getElementById('cast');
var seasonsElement = document.getElementById('seasons');
var episodesElement = document.getElementById('episodes');
var votesElement = document.getElementById('votes');
var epGuideElement = document.getElementById('epGuide');
var showRequest = new XMLHttpRequest();
var showUrl = urlBase + tvId + apiKey + apiLang + '&append_to_response=credits';
showRequest.open('GET', showUrl);
showRequest.send();
showRequest.onload = function() {
var data = JSON.parse(showRequest.responseText);
var title = data.name;
var description = data.overview;
var episodes = data.number_of_episodes;
var seasons = data.number_of_seasons;
var votes = data.vote_average;
var cast = '';
for (i = 0; i < data.credits.cast.length; i++) {
cast +=
'<div style="background-color:#dedede;text-align:center;width:145px;height:215px;margin:10px;padding:10px;display:inline-block;float:left;position:relative;"><img src="http://image.tmdb.org/t/p/w90/'
+ data.credits.cast[i].profile_path
+ '" alt="'
+ data.credits.cast[i].name
+ '" style="margin-top:5px;"><br><div style="width:160px;bottom:20px;left:50%;transform:translate(-50%);position:absolute;"><span style="font-size:14px;">'
+ data.credits.cast[i].character
+ '</span><br><strong>'
+ data.credits.cast[i].name
+ '</strong></div></div>';
}
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
titleElement.insertAdjacentHTML('beforeend', title);
descElement.insertAdjacentHTML('beforeend', description);
posterElement.src = 'http://image.tmdb.org/t/p/w92' + data.poster_path;
castElement.insertAdjacentHTML('beforeend', cast);
episodesElement.insertAdjacentHTML('beforeend', episodes);
seasonsElement.insertAdjacentHTML('beforeend', seasons);
votesElement.insertAdjacentHTML('beforeend', votes);
epGuideElement.insertAdjacentHTML('beforeend', epGuide);
};
How can I select the "season/i" object with the slash and a variable inside its name?
//EDIT:
There you go, the whole code. Hope, we can find a solution.
In the javascript every variable is a hashTable data-structure and you can access/change its items like an array/hashTable for example:
var person = {name:'Siamand',family:'Maroufi'};
we can access the name property of person object by :
var name= person.name;
or
var name =person['name']
so in your case you can change you code into follwoing:
var epGuide = '';
for (i = 1; i <= seasons; i++) {
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 1; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
example snippet:
var response = `
{
"season/1": {
"_id": "5256c89f19c2956ff6046d47",
"episodes": [{
"air_date": "2011-04-17"
}]
}
}
`;
var data = JSON.parse(response);
var seasons = 2;
var epGuide ="";
for(var i=1;i<seasons;i++){
epGuide += '<h3>Staffel ' + i + '</h3>';
for (ii = 0; ii < data['season/'+i].episodes.length; ii++) {
epGuide += '<p>Folge ' + (ii + 1) + '</p>';
}
}
console.log(epGuide);
by the way the api that you are use hasent such result you said before , it something like follwoing, it has a simple array for seasons

eBay API -- can't print buyItNowPrice using Javascript

I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}

eBay API returns low resolution thumbnails

I figured adding &outputSelector=GalleryInfo to the url would provide a higher resolution thumbnail, but that doesn't seem to work. I'm new to JSON, and the tutorial isn't very clear on the exact syntax to add to the URL to make this happen. Thanks!
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APP ID GOES HERE*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.12.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&sortOrder=PricePlusShippingLowest&paginationInput.entriesPerPage=6&outputSelector=GalleryInfo&outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)=New&itemFilter(1).name=MaxPrice&itemFilter(1).value=450.00&itemFilter(1).paramName=Currency&itemFilter(1).paramValue=USD&itemFilter(2).name=MinPrice&itemFilter(2).value=350.00&itemFilter(2).paramName=Currency&itemFilter(2).paramValue=USD&itemFilter(3).name=ListingType&itemFilter(3).value=FixedPrice&keywords=Moto%20x%2016gb>
</script>
It seems like you're looking for the galleryPlusPictureURL: http://developer.ebay.com/Devzone/finding/CallRef/types/SearchItem.html#galleryPlusPictureURL

localStorage issue - Items not displayed (JSON/JQUERY)

I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!

Categories

Resources