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;
};
Related
I would like to apply same piece of code to two objects in JavaScript.
When calling getElementsByClass ,there appears 2 objects in my website.So I would like to apply the same code for both of them.Currently I'm applying it to only one Object (text[0]) and I would like to implement it also to text[1] .
var text=document.getElementsByClassName("th");
var text =text[0];
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
I think you want to do the same thing with using item[0] and item[1] together.
You can create a function. Or call this function by iterating your items too.
var text=document.getElementsByClassName("th");
function myFunc(text) {
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
}
myFunc(text[0]); // call functions with your items.
myFunc(text[1]);
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.
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
I am making a chrome extension which displays glassdoor ratings next to job listings for my university job board.
Everything runs fine when you first load up the page, however the search function of the site (if you try to search/filter out the job list) reloads an inner frame instead of the entire page. When this happens, my content script does not seem to be re-injecting itself into the new elements that are loaded.
This is the content script that I am sending into the page:
var classNames = document.getElementsByClassName("list-item-title");
var i;
for (i = 0; i < classNames.length; i++) {
classNames[i].style.fontWeight = 'bold';
}
var i;
var xhr;
var obj;
var employerNames = document.getElementsByClassName("list-item-body");
document.getElementsByClassName("lst-head-l")[0].insertAdjacentHTML('afterend', "<a href='https://www.glassdoor.com/index.htm'><img src='https://www.glassdoor.com/static/img/api/glassdoor_logo_80.png' title='Ratings Provided by Glassdoor' /></a>");
var apiURL = "https://api.glassdoor.com/api/api.htm?t.p=51863&t.k=kPRnCOceJPO&userip=0.0.0.0&useragent=&format=json&v=1&action=employers&q=";
for (i = 0; i < employerNames.length; i++) {
var xhr = new XMLHttpRequest();
xhr. open("GET", apiURL + employerNames[i].children[2].children[0].innerHTML, false);
xhr.send();
var obj = JSON.parse(xhr.responseText);
if (obj.response.totalRecordCount != 0) {
var child = employerNames[i].children[2].children[0];
var rawRating = obj.response.employers[0].overallRating;
var rating = Math.round(rawRating);
var link = "http://www.glassdoor.com/api/api.htm?version=1&action=employer-overview&t.s=w-m&t.a=c&employerId=" + obj.response.employers[0].id;
var text = "<a href=\"" + link + "\"> <b style=\"color: #7cb228; font-size: 120%;\" title=\" " + rawRating + " \">";
for (var k = 0; k < rating; k++) {
text += "★";
}
for (var k = 0; k < (5 - rating); k++) {
text += "☆";
}
text += "</b>";
child.insertAdjacentHTML('afterend', text);
// employerNames[i].children[2].innerHTML += " <b style=\"color: black\">(" + obj.response.employers[0].overallRating + ") ★ </b>";
}
}
I hope the above makes sense, does anyone have any suggestions?
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!