I have a misunderstanding with localStorage - javascript

I'm currently beginning to learn how to use javascript, and I have a small problem.
I'm making a minigame of 'find the random number', and I'm trying to implement a localStorage savestate that let me keep my game as it was when I closed it, but without success. Here's the part of my JS
where I'm stuck.
let Rndm = Math.floor(Math.random() * 100) + 1;
var tentatives = document.querySelector('.tentatives');
var resultat = document.querySelector('.resultat');
var plusoumoins = document.querySelector('.plusoumoins');
var valider = document.querySelector('.valider');
var essai = document.querySelector('.essai');
var nmbrmax = 1000;
var nmbrtent = 1;
let j1 = document.getElementById("j1");
let j2 = document.getElementById("j2");
var joueur1 = document.getElementById("joueur1");
var joueur2 = document.getElementById("joueur2");
let nomsjoueurs = document.getElementById("nomsjoueurs");
let tour = document.getElementById("tour");
var playerTurn = 0;
const partiesauvee = []
function sauvegarder() {
partiesauvee.push(tentatives.textContent);
partiesauvee.push(resultat.textContent);
partiesauvee.push(plusoumoins.textContent);
partiesauvee.push(nmbrmax);
partiesauvee.push(nmbrtent);
partiesauvee.push(joueur1.value);
partiesauvee.push(joueur2.value);
localStorage.setItem('sauvegard', JSON.stringify(partiesauvee))
}
function refresh() {
const partiesauvee = JSON.parse(localStorage.getItem('sauvegard'));
var tentatives = JSON.parse(localStorage.getItem('sauvegard'));
var resultat = JSON.parse(localStorage.getItem('sauvegard'));
var plusoumoins = JSON.parse(localStorage.getItem('sauvegard'));
var nmbrmax = localStorage.getItem('sauvegard');
var nmbrtent = localStorage.getItem('sauvegard');
var joueur1 = JSON.parse(localStorage.getItem('sauvegard'));
var joueur2 = JSON.parse(localStorage.getItem('sauvegard'));
}
window.addEventListener('DOMContentLoaded', refresh);
When the sauvegarder function is activated, the console.log(localstorage) find all the values,
but I can't find a way to return them to their places. Someone have an idea? Thanks !

You're storing an array. You need to assign each array element to a different DOM element.
function refresh() {
const storage = localStorage.getItem('sauvegard');
if (!storage) { // nothing saved
return;
}
const partiesauvee = JSON.parse(storage);
tentatives.textContent = partiesauvee[0];
resultat.textContent = partiesauvee[1];
plusoumoins.textContent = partiesauvee[2];
nmbrmax.textContent = partiesauvee[3];
nmbrtent.textContent = partiesauvee[4];
joueur1.textContent = partiesauvee[5];
joueur2.textContent = partiesauvee[6];
}

Related

A function doesn't respond in ref.on() even if the result is correct

I have been trying to create an app named workspace. I had asked another question earlier but now the features I have added are more. There is a remarks system. I have tried using different versions of my code and the code I have given has the best version I created. I cannot find an answer to my question on the net so I had to ask it here.
var ref = firebase.database().ref();
function stdRemarks(studentName){
let finalStuff;
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
return finalStuff;
});
}
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith);
for(i=0;i<lengthOfIt;i++){
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
document.getElementById("schoolnameis").innerText = "Dashboard - " + objectToDealWith['i'];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
console.log(stdRemarks(stdiName))
let elementToPush = `<tr><td>${stdiName.replace(/undefined/g, '')}</td><td>${stdClass.replace(/undefined/g, '')}</td><td>${stdEmail.replace(/undefined/g, '')}</td><td>${stdSubject.replace(/undefined/g, '')}</td><td>${stdProjectInfo.replace(/undefined/g, '')}</td><td>${stdRemarks(stdnameName).replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName.replace(/undefined/g, '')}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
So everything is working fine but some stuff here seems to corrupt the whole code. My database looks somewhat like this
Here is the error.
//A warning by firebase.
#firebase/database: FIREBASE WARNING: Exception was thrown by user callback. TypeError: Cannot read property 'replace' of undefined
//An error occuring on the variable `elementToPush` and its part ${stdRemarks(stdnameName).replace(/undefined/g, '') in the code.
Cannot read property 'replace' of undefined
I have to submit this project tomorrow.
your function 'stdRemarks' has a return type of 'void'. either return the the complete ref.on() or move 'finalstuff' outside the .on() function call and make sure the function 'stdRemarks' has the desired return type. in this case this would be a 'string';
function stdRemarks(studentName){
let finalStuff = "";
ref.on("value", function(snapshot){
let keys = Object.keys(snapshot.val().schools[returnCurrentUser()][studentName]['remarks']);
for(i=0;i<keys.length;i++){
let objectToDealWith = snapshot.val().schools[returnCurrentUser()][studentName]['remarks'];
let remark = objectToDealWith[keys[i]]['remark'];
let examiner = objectToDealWith[keys[i]]['examiner'];
let fullRemark = ` ${examiner}: ${remark} | `
finalStuff += fullRemark;
}
});
return finalStuff;
}
I made it work by using this code.
ref.on("value", function(snapshot){
let dashTab = document.getElementById("dashboard_table");
let btn = document.getElementById("csv_blob");
let btn2 = document.getElementById("json_view");
let btn3 = document.getElementById("json_export");
btn.style.display = "block";
btn2.style.display = "block";
$("#json_export").css('display', 'block');
dashTab.innerHTML = "<thead><tr><th>Student Name</th><th>Class</th><th>Email</th><th>Subject</th><th>Project Info</th><th>Remarks</th><th>Project</th><th style='display: none;'>Project Download URL</th><th>Add Remark</th></tr></thead>";
let jsonRecieved = snapshot.val();
let objectToDealWith = snapshot.val().schools[returnCurrentUser()];
let lengthOfIt = Object.size(objectToDealWith)-1;
for(i=0;i<lengthOfIt;i++){
let finalRemark;
let int = i + 1;
let names = Object.keys(objectToDealWith);
let stdName = names[i];
let finalResult = objectToDealWith[stdName];
let stdClass = finalResult['class'];
let stdEmail = finalResult['email'];
let stdSubject = finalResult['subject'];
let stdiName = finalResult['stdname'];
for(var e=0;e<Object.size(objectToDealWith[stdName]['remarks']);e++){
let keys = Object.keys(objectToDealWith[stdName]['remarks']);
let remark = objectToDealWith[stdName]['remarks'][keys[e]]['remark'];
let examiner = objectToDealWith[stdName]['remarks'][keys[e]]['examiner'];
let completeRemark = ` | ${examiner} : ${remark} `
finalRemark += completeRemark;
}
let stdProjectName = finalResult['projectname']
let stdProjectInfo = finalResult['projectinfo'];
let stdProjectLink = finalResult['projectlink'];
let elementToPush = `<tr><td>${stdiName}</td><td>${stdClass}</td><td>${stdEmail}</td><td>${stdSubject}</td><td>${stdProjectInfo}</td><td>${finalRemark.replace(/undefined/g, '')}</td><td><a href=${stdProjectLink}>${stdProjectName}</a></td><td style='display:none;'>${stdProjectLink}</td><td id="${stdName}" style='text-align:center;' onclick="closeThatSomeThing();getIdOfTd(this.id)">&#x2795</td></tr>`;
dashTab.innerHTML += elementToPush;
}
});
What i did here was that i turned i to e in the second loop and it worked...

Prototype function no longer working, coming up as undefined

I have no idea what I did wrong. It worked before I uploaded to github.io so I'm suspicious I messed up some branches and am now stuck with an older file. I'm impossibly stuck and just need an outside perspective to figure it out.
It's a program to help order pizza (all in js/jquery), it's no longer adding up the variables and returning an order total. It says var total is undefined, and I'm not completely sure whether it's my equations or variables. I had it working fine before so I know it's possible with my code, I think I just made a mistake somewhere in the process of switching/adding branches that bungled it.
function order(sidesOrderedReduced, pizzaSauceReduced, beveragesOrderedReduced, dessertsOrderedReduced, pizzaToppingsReduced, zipcodeAddress, cityAddress, streetAddress, total){
this.sidesOrderedReduced = sidesOrderedReduced;
this.beveragesOrderedReduced = beveragesOrderedReduced;
this.dessertsOrderedReduced = dessertsOrderedReduced;
this.pizzaSauceReduced = pizzaSauceReduced;
this.pizzaToppingsReduced = pizzaToppingsReduced;
this.zipcodeAddress = zipcodeAddress;
this.cityAddress = cityAddress;
this.streetAddress = streetAddress;
this.total = total;
}
var sidesListed = [];
var sidesOrdered = [];
sidesOrderedReduced = sidesOrderedReduced || 0
var sidesOrderedReduced;
var beveragesListed= [];
var beveragesOrdered = [];
var beveragesOrderedReduced;
beveragesOrderedReduced = beveragesOrderedReduced || 0
var dessertsListed = [];
var dessertsOrdered = [];
var dessertsOrderedReduced;
dessertsOrderedReduced = dessertsOrderedReduced || 0
var pizzaSauceListed = [];
var pizzaSauce = [];
var pizzaSauceReduced = [];
pizzaSauceReduced = pizzaSauceReduced || 0
var pizzaToppingsListed = [];
var pizzaToppingsOrdered = [];
var pizzaToppingsReduced;
pizzaToppingsReduced = pizzaToppingsReduced || 0
var total;
var zipcodeAddress = $("input#zipcodeAddress").val();
var cityAddress = $("input#cityAddress").val();
var streetAddress = $("input#streetAddress").val();
var newOrder = new order(sidesOrderedReduced, beveragesOrderedReduced, dessertsOrderedReduced, pizzaSauceReduced, pizzaToppingsReduced, zipcodeAddress, cityAddress, streetAddress, total);
order.prototype.total = function(){
return this.beveragesOrderedReduced+this.sidesOrderedReduced+this.dessertsOrderedReduced+this.pizzaSauceReduced+this.pizzaToppingsReduced;
}
$("input:checkbox[value=sides]:checked").each(function(){
sidesListed.push($(this).attr("id"));
sidesOrdered.push(5);
sidesOrderedReduced = sidesOrdered.reduceRight(function(a,b){return a+b;});
return sidesOrderedReduced;
});
$("input:checkbox[value=pizzaSauce]:checked").each(function(){
pizzaSauceListed.push($(this).attr("id"));
pizzaSauce.push(10);
pizzaSauceReduced = pizzaSauce.reduceRight(function(a,b){return a+b;});
return pizzaSauceReduced;
});
$("input:checkbox[value=pizzaToppings]:checked").each(function(){
pizzaToppingsListed.push($(this).attr("id"));
pizzaToppingsOrdered.push(1);
pizzaToppingsReduced = pizzaToppingsOrdered.reduceRight(function(a,b){return a+b;});
return pizzaToppingsReduced;
});
$("input:checkbox[value=beverages]:checked").each(function(){
beveragesListed.push($(this).attr("id"));
beveragesOrdered.push(3);
beveragesOrderedReduced = beveragesOrdered.reduceRight(function(a,b){return a+b;});
return beveragesOrderedReduced;
});
$("input:checkbox[value=desserts]:checked").each(function(){
dessertsListed.push($(this).attr("id"));
dessertsOrdered.push(5);
dessertsOrderedReduced = dessertsOrdered.reduceRight(function(a,b){return a+b;});
return dessertsOrderedReduced;
});
$("ul#orders").append(
"<li><span class='orderInfo'>Order</span></li>");
$(".orderInfo").last().click(function(){
$("#show-info").show();
$(".sides").text(sidesListed);
$(".pizzaSauce").text(pizzaSauceListed);
$(".pizzaToppings").text(pizzaToppingsListed);
$(".beverages").text(beveragesListed);
$(".desserts").text(dessertsListed);
$(".zipcodeAddress").text(newOrder.zipcodeAddress);
$(".streetAddress").text(newOrder.streetAddress);
$(".cityAddress").text(newOrder.cityAddress);
$(".total").text(newOrder.total);
});
//$('input:checkbox').removeAttr('checked');
$("input#zipcodeAddress").val("");
$("input#cityAddress").val("");
$("input#streetAddress").val("");
});
});
Change
$(".total").text(newOrder.total);
to
$('.total').text(newOrder.total());
total is a method. You just used it as a property.

Javascript: window.confirmation

I have a function:
function placeOrder(price, productList) {
var bulletinBoardItem = Number(productList.box1.value);
var stickersItem = Number(productList.box2.value);
var cutoutsItem = Number(productList.box3.value);
var trimmerItem = Number(productList.box4.value);
var resourceBooksItem = Number(productList.box5.value);
var price = new Array(5);
price[0] = 12;
price[1] = 1;
price[2] = 6;
price[3] = 3;
price[4] = 20;
var sumBB = bulletinBoardItem * price[0];
var sumStickers = stickersItem * price[1];
var sumCutouts = cutoutsItem * price[2];
var sumTrimmer = trimmerItem * price[3];
var sumRB = resourceBooksItem * price[4];
}
and I have a window.confirm box that I need to reference the above function from, but none of the variables are recognized in that function. I don't understand what I'm doing wrong here.
<input type="button" onClick="placeOrder()" value="Place Order">
<p id = "order"></p>
<script>
function placeOrder(quantity, price, productList) {
var r = confirm("You've ordered Bulletin Boards");
if (r) {
window.alert("Your order has been placed!!!")
} else {
window.alert("Your order has been canceled.");
}
document.getElementById("order").innerHTML = txt;
}
</script>
You are using txt which is not defined :
document.getElementById("order").innerHTML = txt;
Thus, try to change txt by any defined string and your script will not be failed

Having trouble with image preload code

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.
1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

Loop through elements with greasemonkey

I have the following working code on greasemonkey:
var qtt = 100;
var filler1 = document.getElementById("s1_0");
var filler2 = document.getElementById("s2_0");
var filler3 = document.getElementById("s3_0");
var filler4 = document.getElementById("s4_0");
var filler5 = document.getElementById("s5_0");
var filler6 = document.getElementById("s6_0");
var filler7 = document.getElementById("s7_0");
filler1.value = qtt;
filler2.value = qtt;
filler3.value = qtt;
filler4.value = qtt;
filler5.value = qtt;
filler6.value = qtt;
filler7.value = qtt;
Where the "sN_0" are the names of inputs, the code works, but I was wondering if there is a better way to do the same, to loop through all the id names or something.
here is a simple loop doing that your code does
var qtt=100;
for (var i =1;i<8;i++){
document.getElementById("s"+i+"_0").value=qtt
}
If you can use jQuery, try the following.
var qtt = 100;
$('[id]').each(function() {
if(/^s\d_0$/.test(this.id)) {
this.value = qtt;
}
});
Demo

Categories

Resources