I am trying to display the values that have been stored in an array within local storage. I have been able to store the values in local storage and add other values on the click of a button but I cant retrieve the values back out and display them on a page.
This is my code that adds values to local storage.
$("#player1Link").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
if (a.indexOf(chosenPlayerId) === -1) {
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
alert("Pushed in");
} else {
alert("Already in favourites");
}
} else {
var a = [];
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
}
})
I want to be able to click a button to retrieve the values and display them on the page but I can figure out the code to go in this function.
$("#playerRetrieve").click(function() {});
If anyone could help it would be much appreciated.
I made a jsfiddle, it seems to work there: jsfiddle
try:
localStorage.getItem('player1Favourite');
or:
localStorage.player1Favourite
You might want to have a look at:
this topic
or at
Mozilla
I'm not exactly sure I understand you correctly, because if you just want to retrieve the values you can use the same code, just remove the insertion from your code and change the jQuery selector.
$("#playerRetrieve").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
// Do what you want with the values, which are now in a.
}
});
Related
Greets, so I I'm trying to learn jquery/javascript storage and ran into an issue where I am building a navigation that should remember and place you where you last were if you refresh the page (that's why i use sessionStorage rather then localStorage).
But I can't seem to change the sessionStorage variable to the new location, nor figure out a functional way to get the user back on refreshing the page.
This is what I currently have.
$(function() {
sessionStorage.setItem('position', '.first');
var location = sessionStorage.getItem('position');
$('li', this).click(function() {
cls = $(this).text();
if('.' + cls != location) {
$(location).slideToggle(400);
$('.' + cls).delay(400).slideToggle(400);
sessionStorage.setItem('position', '.' + cls)
console.log(location)
};
});
});
https://jsfiddle.net/Unkn0wn96/ndj9sqpe/
The code works in an very odd way, rather then how it's intended, including never changing the value when I console.log(location).
I made some further testing on this and found a 'more' working way in the was that the sessionStorage does change to something, yet it not being usefull.
https://jsfiddle.net/Unkn0wn96/nkbtykkr/
but yet, they elements don't toggle as they should, including that when I console log sessionStorage.position it returns NaN. Also for some odd reason I can't store sessionStorage.position within a variable, it just refuses to change its value. I have no clue why this is happening.
So I was finally able to solve my issue with sessionStorage, since there was not much of help I'd assume the information regarding the case was limited and so wish to share my solution. All thought it does not work fully as intended it does execute it's main function.
$(function() {
$('button').on('click', function() {
var msg = '.'+$(this).text();
localStorage.setItem('color', 'blue') //Default (does not matter since the if statement does not register)
if(msg != '.' + localStorage.color) { // DOES NOT REGISTER
if(localStorage.length > 0) {
localStorage.removeItem('color')
console.log('localStorage.length : ' + localStorage.length)
};
localStorage.setItem('color', msg)
console.log(localStorage.color)
} else {
console.log('cancelled')
}
});
});
https://jsfiddle.net/mdqjoz69/4/
So what I finally was able to achieve was to make a localStorage key change it's value regarding of what button you press.
What I failed to achieve was being able to check the stored data to not execute whenever you store something that have already been stored. There might be a work around for this. But since the code serves its main purpose I'll let it slide.
How can I save my HTML element tag data after user closed the browser. For example
<div class="classOne" data-random="50">
And i used jQuery to change the data attribute
$(".classOne").attr("data-random","40")
And if the user close out the browser and comes back the value for data-random will be 40. How can I achieve this ?
Have you tried looking at localStorage?
LocalStorage allows you to store data within the browser. So even after the user close out the browser and comes back, you still have the value stored in your LocalStorage
Here is a sample code on how you can use local storage:
localStorage.setItem("data-random", 40);
You can set it with:
localStorage.setItem("data-random","40")
And later load it:
localStorage.getItem("data-random")
If you want to store JSON objects, you should use stringify() before saving and JSON.parse() after loading.
try localStorage.
https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage
$(document).onload(function(){
if(localStorage.rendomData){
var data = localStorage.rendomData - 10
localStorage.set(randomData,data)
}
else{
localStorage.set(randomData,50)
}
})
I hope this helps.
The easiest way to achive it is to use cookies. Just take this plugin: https://github.com/carhartl/jquery-cookie and then above the line:
$(".classOne").attr("data-random","40")
add:
var randValue;
if (typeof $.cookie('my-rand-value') == undefined) {
// generate random value
randValue = generateRandomValue //assign random value to variable
$.cookie('my-rand-value', randValue)
}
else {
randValue = $.cookie('my-rand-value')
}
at the end change static value to your variable:
$(".classOne").attr("data-random",randValue)
You can do that by using cookies as well as by using local storage -
for local storage first store first try to get value if it is stored like -
if(localStorage.getItem("data-random") != null){
return localStorage.getItem("data-random");
} else {
return 50;
}
and when user changes the value you can save that value by -
localStorage.setItem("data-random", value);
Use Jquery function beforeunload and save it into localStorage.
$(window).on('beforeunload', function() {
// Put the object into storage
localStorage.setItem('data', $(".classOne").attr("data-random"));
});
To Retrieve the data from storage whenever your page opens.
var retrievedData = localStorage.getItem('data');
So, I've got a notepad extension for Google Chrome that syncs and displays stored notes from a user. Currently my problem is as follows.
When the extension is run for the first time after download, the word 'undefined' is displayed in the editable div (id = edit_notepad). I want it to just be blank instead of displaying anything. Obviously, I know its undefined because the user hasn't been able to add any text yet.
Picture of what's displayed on initial run:
From my content script, here are my chrome.storage get and set functions (which do work):
document.body.onload = function() {
chrome.storage.sync.get("edit_notepad", function(items) {
if (!chrome.runtime.error) {
console.log(items);
document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
}
});
}
document.getElementById("edit_notepad").onkeyup = function() {
var d = document.getElementById("edit_notepad").innerHTML;
chrome.storage.sync.set({ "edit_notepad" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
}
I presume I'm going to need some sort of if statement, but after hours of playing around, I'm lost as to what exactly it'd contain. The issue I've kept running into is that whatever I set the initial value of edit_notepad to, it always reverts back to "undefined" even when a user has written some notes! e.g. "This is a notes test" would revert back to "undefined" when the notepad is closed and reopened.
Well, an easy way to do this would be to specify a default value in your chrome.storage.sync.get(). Doing so would apply the default value when the key does not exist in the storage. However, given that you are replacing any contents which might already exist, the better solution would be not to set the contents when you have no value, or an invalid value, stored. The only valid value will be a string. This will prevent you from overwriting any default value supplied by the webpage when you have no value stored. Thus, an if statement something like the following should work (alternately, you could test for !== 'undefined':
document.body.onload = function() {
chrome.storage.sync.get("edit_notepad", function(items) {
if (!chrome.runtime.error) {
console.log(items);
if(typeof items.edit_notepad === 'string') {
document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
}
}
});
}
Note: Storing the contents of the editable <div> on every key will result in many users running into both the MAX_WRITE_OPERATIONS_PER_MINUTE and MAX_WRITE_OPERATIONS_PER_HOUR quotas. You will need to have some other criteria for writing to storage.sync. Perhaps you could temporarily store the value in storage.local and only to storage.sync every couple of minutes.
I'm trying to load data from a JSON file that is based off of the option that is selected by the user. I have it working but I know it can be written much more efficient and I'm having a hard time finding a good place to start. I'll include an example of my code below, but it's pulling in various counties based off of the state you choose. You'll notice though that I'm checking each value with an else if statement to load in the correct data. I'm sure there has to be a way to load what I need but without 49 other else if statements.
HTML:
<select id='test-select'>
<option>AL</option>
<option>AK</option>
<option>AZ</option>
</select>
JS:
var cities = [];
$.getJSON('/assets/shared/misc/counties.json', function(json) {
// push json to data to cities array
cities.push(json);
// map over each item item
$('.state-names').map(function(index) {
// load in json data based off of select option
$('#test-select').on('change', function() {
var target = $('#test-select option:selected').val();
console.log(target);
if (target == 'AL') {
$('.state-names').text(cities[0].AL);
} else if (target == 'AK') {
$('.state-names').text(cities[0].AK);
} else if (target == 'AZ') {
$('.state-names').text(cities[0].AZ);
} else if (target == 'AR') {
$('.state-names').text(cities[0].AR);
} // end else if block
}); // end test select function
}); // end map function
console.log(cities);
}); // end getJSON call
This is just the condensed version, but it's basically this plus many more options and else if's. Is there a way I can somehow set an index to whatever state is selected to match the key in the JSON file without having to make so many calls? Any help is greatly appreciated. If I left out any important details I can certainly share more information. Thanks guys.
You can simply use the value of target as property name:
$('.state-names').text(cities[0][target]);
See Access / process (nested) objects, arrays or JSON
Hi guys so i have a form which takes in data like item name, code etc, so when i press the enter button...iv used json stringify and get an alert of what is stored in the local storage. However when i click reset and create a new item it just shows the new item, is there anyway i could store all my items created in local storage...? this is part of my coding. Im a beginner so please excuse if the question is too simple
Thanks
$('#myBox #EnterButton').click(function() {
ItemData = {
'ItemCode' : $('#ItemCode').val(),
'ItemName' : $('#ItemName').val()
};
localStorage.ItemData=JSON.stringify(ItemData);
$('#myBox').slideUp();
});
...
$('#myBox2 #EnterButton').click(function() {
if (localStorage.ItemData) {
alert(localStorage.ItemData);
ItemData = JSON.parse(localStorage.ItemData);
}
if (ItemData.ItemCode) {
$('#myBox #ItemCode').val(ItemData.ItemCode);
}
if (ItemData.ItemName) {
$('#myBox #ItemName').val(ItemData.ItemName);
}
})
and i have declared itemdata as a public variable. Hope its clear. TIA
You have to organize the way ÿou are using localStorage (a getter/setter class might help with maintenance). From your code above, it seems you are always overriding localStorage.ItemData with the values just inserted.
The solution would be for localStorage.Items to be an array and whenever you insert in that array, iterate over it to see if it's not already added (based on itemCode for instance) and override or insert a new item.
I presume this is enough for playing around. A more advanced concept than localStorage and used for slightly different purpuses would be pouchdb - websql in the browser.
Sounds like if you want multiple items to be stored, you should be using an array of itemData objects. You'll then have to parse this (array), and use something like Array.push(newItem) then stringify it again before saving it.
var allItems = localStorage.getItem('ItemData');
if(allItems == null) {
localStorage.setItem('ItemData', JSON.stringify([ItemData]));
} else {
allItems = JSON.parse(allItems);
allItems.push(ItemData);
localStorage.setItem('ItemData', JSON.stringify(allItems));
}