Local Storage display problems - javascript

i'm trying to use localstorage to append recent city searches from user to a form element.
The problem is now im very unsure of how to progress further if .innerHTML wipes out all text
when it's putting anything into the element. the end goal would be for the form element to look something like
athens
paris
chicago
any ideas on how to implement this?
new to local storage so would appreciate any help
here's an example of the code :)
// HTML
<form class="recent-search" id="demo"></form>
// JAVASCRIPT
function setStorage() {
// here i'm trying to store nameValue to localstorage
localStorage.setItem('', nameValue);
}
setStorage()
function getValue() {
// now i'm getting nameofcity from localstorage
return localStorage.getItem('nameofcity');
}
// console logging it so i can make sure it's working (it is)
console.log(getValue());
function myFunction() {
// now i set the innerHTML of the element with the ID of "demo" to be "1. "nameofcity"
document.getElementById("demo").innerHTML = '1. ' + localStorage.getItem('nameofcity');
}
myFunction();
if you'd like more context heres the github repository https://github.com/LukeMcHenry311/Server-Side-Weather

You're saving the value to the key of an empty string and then trying to retrieve the key of nameofcity, which you probably didn't save it to. localStorage works by key-value pairs. You can always go to your browser's dev tools (usually by hitting F12), and under Application tab you can see what's in your local storage
It should be something like
function setStorage() {
localStorage.setItem('nameofcity', nameValue);
}

Related

I was wondering if someone could teach me how to use cookies in my code

I'm trying to make a "Window.alert game" in a browser window for fun, but I can't figure out how to use cookies to save player data if they mess up or close the window. Can someone help me?
LocalStorage is indeed your best option for saving data semi-permanently. One thing to remember is that localStorage only supports strings, so if you need to store more complex objects, you should JSON.stringify them (and JSON.parse the result when loading data).
A simple pattern is to use a single object to store your state, and to save this state to localStorage whenever a change is made to it (so that your latest data is always persisted). You can also listen to the window.beforeUnload method to save your state right before the window closes, but this may not always work (eg: if your browser or tab closes unexpectedly).
Here is an example of what you can do:
// saves your state to localStorage
function save(state) {
localStorage.setItem('state', JSON.stringify(state));
}
// execute code when the document is loaded
document.addEventListener('DOMContentLoaded', function () {
// load your state from localStorage if it has been previously saved
// otherwise, set the state to an empty object
var state = JSON.parse(localStorage.getItem('state')) || {};
// show your name if previously saved
// otherwise, prompt for a name and save it
if (state.name) {
alert('Your name is: ' + state.name);
} else {
state.name = prompt('What is your name?');
save(state);
}
});
To clear localStorage, you can call localStorage.clear().

How to save String value and print it on another page using Google Chrome storage API

I am looking to take user input in and then saving that user input using the google chrome storage api but I cannot find any useful reasources on this topic.
I have 2 elements that I would wish to save permanently using JS:
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
I want to create an 2 arrays, one that holds the title values and one that holds the url values, then I want to print those values out on another page.
You can use chrome.storage.local object to accomplish that.
If you need to store data in the chrome storage use the following sentence:
chrome.storage.local.set({'titles': [title]});
chrome.storage.local.set({'urls': [url]});
Now, if you want to retrieve the current data in the chrome storage use the following:
let newTile = "new title";
chrome.storage.local.get('titles', function(titles){
titles.push(newTile);
chrome.storage.local.set({'titles': titles});
});
let newUrl = "http://.....";
chrome.storage.local.get('urls', function(urls){
urls.push(newUrl);
chrome.storage.local.set({'urls': urls});
});
Important: What is missing here, are the conditions to check current data in the local storage.
Hope this helps!

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

Set data from localStorage when user is connected

I have been working on a save file for my game. The save file IS working, and console.log displays proper values:
function saveGame(){
localStorage.setItem('game', JSON.stringify(game));
}
function loadGame(){
var retrievedObject = localStorage.getItem('game');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
Image of the logs: https://s28.postimg.org/bslusmagt/Untitled.png
I'm still new to all this as I have started learning JS couple of months ago. Right now my guess is that when the page is loaded, I'm supposed to set all these values. Trying the next thing i get "null" in console.log
console.log(JSON.parse(localStorage.getItem('game.plutonium')));
I thought values could be set something like:
game.plutonium = localStorage.getItem('game.plutonium');
But it doesn't work. Whats the trick here?
Here is my full JS code, just in case: http://pastebin.com/yM2wz410
Values are defined from line 1, and save / load file is on the line 350-356.
Why doesn't my method work?
function saveGame(){
var savefile = JSON.stringify(game);
localStorage.setItem("game", savefile);
}
function loadGame(){
var savefile = localStorage.getItem("game");
if (savefile === null) {
return;
}
game = JSON.parse(savefile);
}
Method above seems to have completely solved the problem. Thanks :)
JSON.stringify() changes the object you give it into a string (which can be stored very easily). But: you can't navigate that string anymore via string.key
To translate that json string back into a object (that can be navigated again), you need to use JSON.parse().
Your problem above is, that you store the whole object (as json) into the storage with key game and then try to get the item game.plutonium from the storage. Note that you didn't save anything as game.plutonium.
You need to first fetch the whole json string via localStorage.getItem('game'), then parse the string back to an object and only then you can navigate over it again like game.plutonium.
var game = JSON.parse(localStorage.getItem('game'))
var plutonium = game.plutonium;

Categories

Resources