Store same local storage item multiple times - javascript

I can enter text and search for data, and then store that data, in this case a name.
localStorage.setItem("name", currentWeather.name);
Using the for loop (while on the same page), I can do multiple searches and the name data for each search is displayed on the page.
for (var i = 0; i < localStorage.length; i++){
$("#record").append(localStorage.getItem(localStorage.key(i)));
}
I now want to be able to store each name, so when I return to that page it still shows them all. Currently local storage is only capable of storing the latest name. I am guessing I need to create an array that I can store each search term into but not sure how to go about it. I have seen some suggest it can be done this way and other people have simply said it is not possible.
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
//check not empty
if (city !== ''){
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + "&APPID",
type: "GET",
dataType: "jsonp",
success: function(weatherData){
var currentWeather = showCurrent(weatherData);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
});
function showCurrent(currentWeather) {
console.log(currentWeather);
console.log(currentWeather.name);
if (typeof(Storage) !== "undefined") {
// Store
//saves name in local storage (for histoy list)
localStorage.setItem("name", currentWeather.name);
//saves name in session storage for current use
sessionStorage.setItem("name", currentWeather.name);
// Retrieve
// Retrieves name from session storage
document.getElementById("name").innerHTML = sessionStorage.getItem("name");
// Retrieves name from local storage for history list
document.getElementById("name").innerHTML = localStorage.getItem("name");
// Outputs all locations searched
for (var i = 0; i < localStorage.length; i++){
$("#record").append(localStorage.getItem(localStorage.key(i)));
}
}
else {
document.getElementById("error").innerHTML = "Sorry, your browser does not support Web Storage...";
}

localStorage only stores strings, so to store an array or object you use JSON.stringify.
var names = [ 'Philbo', 'Nipwip', 'Henk' ];
localStorage.setItem( 'names', JSON.stringify( names ) );
And you retrieve it with JSON.parse.
var names = JSON.parse( localStorage.getItem('names') );
Let's get silly and append a new name in a one-liner:
localStorage.setItem( 'names',
JSON.stringify(
JSON.parse(
localStorage.getItem( 'names' ) || '[]'
).concat([ 'Billiam' ])
)
)
For your problem:
var weather = [];
function showCurrent(currentWeather) {
weather.push( currentWeather.name );
if (typeof(Storage) !== "undefined") {
localStorage.setItem("weather", JSON.stringify( weather ) );
...
document.getElementById("name").innerHTML = JSON.parse( localStorage.getItem("weather") );

At first glance, it seems as though you are setting the same key over and over, so you'd only ever have one key-value pair in your localStorage ("name"). Even if you stored the currentWeather.name value in an array, you'd still end up reassigning the same "name" key over and over.
Instead, you could make the assigned key dynamic, such as
localStorage.setItem(currentWeather.id, currentWeather.name);
Or something to that effect. I don't know what properties your currentWeather object will have. You could even simply assign the name value to both arguments of setItem.

Related

Create multiple localStorage entries automatically

I want to create a login by using js. For this, I want to use localStorage. It's easy to store just one email, since you can give it a key. But what if I want to create multiple entries for email? I've thought about using a variable (let's call it x) which is 0 when there is nothing in localStorage. It could be set to +1 any time a new Email is added. My idea would then be to write:
let x = 0;
function addMail{
usrInput = document.getElementById("userEmail").value;
x = x + 1;
localStorage.setItem("email" + x, usrInput);
}
That's the register part. But I'm lost when It comes to logging in. How can I check if that email the user types into the text-input (id = "usrEmail") is identical to any entry in localStorage?
Instead of storing email as the value in the local storage, you can store a whole array of emails by serializing it as JSON.
Push new email:
const emailsInStorage = JSON.parse(localStorage.get('emails') || '[]');
emailsInStorage.push('new#email.com');
localStorage.set('emails', JSON.stringify(emailsInStorage));
Check if email exists in the list:
const emailsInStorage = JSON.parse(localStorage.get('emails') || '[]');
const exists = emailsInStorage.includes('new#email.com');
Edit #1
Instead of constructing an array and serializing it as JSON, you can go ahead with your idea of storing different emails under different keys (email1, email2, etc.). Still, you'll have to store also the number of email keys you have already stored.
I attached an example you can play around with, but the JSON approach is better.
function getEmailsCount() {
return Number(localStorage.getItem('emails.count'));
}
function getEmailByIndex(index) {
return localStorage.getItem(`emails.${index}`);
}
function saveEmail(email) {
const nextIndex = getEmailsCount() + 1;
localStorage.setItem(`emails.${nextIndex}`, email);
localStorage.setItem('emails.count', nextIndex);
}
function isEmailExists(email) {
const emailsCount = getEmailsCount();
for (let i = 0; i <= emailsCount; i++) {
if (getEmailByIndex(i) === email) return true;
}
return false;
}
saveEmail('email1#gmail.com');
saveEmail('email2#gmail.com');
saveEmail('email4#gmail.com');
saveEmail('email5#gmail.com');
console.log(isEmailExists('email1#gmail.com')); // true
console.log(isEmailExists('email2#gmail.com')); // true
console.log(isEmailExists('email3#gmail.com')); // false
console.log(isEmailExists('email4#gmail.com')); // true
console.log(isEmailExists('email5#gmail.com')); // true
console.log(isEmailExists('email6#gmail.com')); // false

My variables wont save in the array, they get replaced? help me

I am trying to save my variables in an array. Theses variables are written in by the user and saved to localStorage when a button is pressed. On my other html page i reach these variables and put them in 3 different arrays(the variables, that go in three arrays). Then the user writes in new text and save to the variables. Now to the problem. The newly created variables don't add to the array, they replace. I'm thinking this is due to to the same variable name however I can't find an solution.
I have tried to change variable names etc for saving the new variable but cant find solution.
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar= localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = [];
var arrayLiter = [];
var arrayDatum = [];
arrayKostnad.push(TankaKostnadVar,);
arrayLiter.push(TankaLiterVar,);
arrayDatum.push(TankaDatumVar,);
document.write(arrayLiter,arrayKostnad,arrayDatum); //Ignore this, just test
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
I expect the array to add the variable. So if the user writes an 5 the array should first be [5] then when the user writes an 8 the array should be [5,8]
If you don't want use JSON, you can save string comma separated and, when necessary, transform the items to numbers. To transform in numbers you can use map function or a for. Localstorage only save strings, so if you need to be back to numbers you need to use JSON.parse or use function parseInt, that is global.
//Retrieve saved items from localstorage
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar"); // "1,2"
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
TankaKostnadVar += "," + document.getElementById("tankaKostnad").value;
TankaLiterVar += "," + document.getElementById("tankaLiter").value;
TankaDatumVar += "," + document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
// if you want to transform TankaKostnadVar and others two, just do like this
TankaKostnadVar.split(','); // result: ['1', '2']
// if you want to transform to number
TankaKostnadVar = TankaKostnadVar.split(',').map( function(number) {
return parseInt(number)
} );
The split function of string, breaks a strings in parts separated by one string. In this case, breaks a string separated with comma. So "1,2" turns into ['1', '2'].
If you want to keep adding to the array you'll need to push the entire array you're holding in memory up to localStorage after appending a new element. Alos, localStorage only stores string values so if you want to maintain the Array structure you'll have to use JSON.stringify() before running setItem() and then JSON.parse() next time you access those values with getItem().
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", JSON.stringify( [TankaKostnadVar] ));
localStorage.setItem("StorageLiterVar", JSON.stringify( [TankaLiterVar] ));
localStorage.setItem("StorageDatumVar", JSON.stringify( [TankaDatumVar] ));
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = JSON.parse(TankaKostnadVar);
var arrayLiter = JSON.parse(TankaLiterVar);
var arrayDatum = JSON.parse(TankaDatumVar);
// Now you have arrays with data, but I don't know what you want to do with them...
// you could add more values like this (still page 2)...
arrayKostnad.push('new value 1')
arrayLiter.push('new value 2')
arrayDatum.push('new value 3')
localStorage.setItem("StorageKostnadVar", JSON.stringify( arrayKostnad ));
localStorage.setItem("StorageLiterVar", JSON.stringify( arrayLiter ));
localStorage.setItem("StorageDatumVar", JSON.stringify( arrayDatum ));
// now check the values again
var TankaKostnadArr = JSON.parse(localStorage.getItem("StorageKostnadVar"));
var TankaLiterArr = JSON.parse(localStorage.getItem("StorageLiterVar"));
var TankaDatumArr = JSON.parse(localStorage.getItem("StorageDatumVar"));
document.write(TankaKostnadArr, TankaLiterArr, TankaDatumArr)
And this is what I would do to clean things up a little...
// Import these functions and variables to any file that needs to interact with LocalStorage
var storageKeys = ["StorageKostnadVar","StorageLiterVar","StorageDatumVar"];
function addToArray(key, val, arrObj) {
arrObj[key].push(val)
}
function storeAllLocalStorage(arrayObject) {
Object.keys(arrayObject).forEach(key=>{
localStorage.setItem(key, JSON.stringify(arrayObject[key]));
})
}
// Use above functions when needed
var storedArrays = storageKeys.reduce((acc,key)=> {
var val = JSON.parse(localStorage.getItem(key));
if (typeof val === 'array') return {...acc, [key]:val};
return {...acc, [key]:[val]};
},{})
addToArray("StorageKostnadVar", document.getElementById("tankaKostnad").value, storedArrays);
addToArray("StorageLiterVar", document.getElementById("tankaLiter").value, storedArrays);
addToArray("StorageDatumVar", document.getElementById("tankaDatum").value, storedArrays);
storeAllLocalStorage(storedArrays)
You are simply using localStorage.setItem which saves your values with the given key. If the key exists, it will replace the value. Before you do a .setItem, get the value from the local storage first, then parse it to array so that you can finally push the new user inputs to that parsed array. Then you can .setItem to replace the "outdated" value from the localStorage.
UPDATE Example:
Sorry for leaving this hangin without an example. Here it is:
// Get array from local storage
const stringifiedArray = localStorage.getItem('myCollection');
// If there is no 'myCollection' from localStorage, make an empty array
const myCollection = stringifiedArray ? JSON.Parse(stringifiedArray) : [];
myCollection.push('My new item added'); // update array
localStorage.setItem('myCollection', JSON.stringify(myCollection)); // save

How to get localStorage array data.

I am new to localStorage. I set array in localstorage so how can get this value. My code as below.
$scope.lineItemID = data.id;
var itemtemp={
"itemid": data.id,
"qty": $scope.quantity
};
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
itemqty.push(itemtemp);
localStorage.setItem("itemqty", JSON.stringify(itemqty));
So my question is how can I get itemqty.qty as per itemid from localstorage
try Below code
$.each(data.itemqty, function(index, item) {
// append data using html //use item.name
});
OR try below
$.each(data, function(idx, item){
// append data using html
//
});
You are quite simply creating an array of objects itemqty and saving it in the browser's storage. When you do this:
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
//itemqty is available to you as an array of objects.
Suppose you are looking for the associated quantity for some itemid stored in the variable foo. You just need to traverse the parsed itemqty like so:
$.each(itemqty, function( index, value ) {
if(value.itemid == foo)
{
console.log(value.qty);
// value.qty is the required quantity
}
});
items=JSON.parse(localStorage.getItem('itemqty'));
for (var i = 0; i < items.length; i++) {
if(items[i].itemid === itmId) {
return items[i].qty;
}
}
I am using it & it's working

search history with localStorage variable in HTML

I'm creating an jQuery mobile app with PhoneGap and I want to list old search results (entered by a form and stored in localStorage).
There are two different problems to solve:
1) I would store a result in a localStorage array and if the user is searching a second time, the result should be added to the array after the old result like: city[0] = "New York", city[1] = "Paris" ... how can I save and read a string in an array, like:
localStorage.setItem('city[i]', $('#city').val());
or
localStorage.getItem('city[i]');
2) Now I want to show the search history. I've tried this, but:
I don't know how to display the localStorage array or variable in a html list and ...
if no variable in localStorage, the website doesn't load.
<div id="lastResults"></div>
<script>
var history = "";
if (localStorage.getItem("history") !== "") {
var history = localStorage.getItem("history");
}
if ( history !== "") {
$("#lastResults").html(
"<b>Last Results:</b>" +
"<ul data-role=\"listview\" data-inset=\"true\" >" +
"<li> " + document.write(history) + " </li>" +
"</ul>"
);
}
</script>
LocalStorage stores key value pairs where both the key and the value are strings. One way to get around this is to use a JSON object to store your data and use JSON.stringify and JSON.parse to change the data from object to string and back.
EXAMPLE:
var historyObj = { city: [] };
function onLoad() {
if(localStorage.getItem('history')) {
historyObj = JSON.parse(localStorage.getItem('history'));
}
}
function addHistory(dataToSave) {
historyObj.city.push(dataToSave);
localStorage.setItem('history',JSON.stringify(historyObj));
}
<div id="lastResults"></div>
<script type="text/javascript">
//To Check and show previous results in **lastResults** div
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
var oldhistoryarray = historyTmp.split('|');
$('#lastResults').empty();
for(var i =0; i<oldhistoryarray.length; i++)
{
$('#lastResults').append('<p>'+oldhistoryarray[i]+'</p>');
}
}
//Storing New result in previous History localstorage
if (localStorage.getItem("history") != null)
{
var historyTmp = localStorage.getItem("history");
historyTmp += '|Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
else
{
var historyTmp = 'Paris|Pakistan|China|US';
localStorage.setItem("history",historyTmp);
}
</script>
Note I have used jquery for code shortening.

Ensuring Unique Json

I apologise if this has been asked before but I can't seem to find a solution from other posts on here.
I'm trying to build a json array in local storage (which is fine) but want to check if an entry already exists before adding new values.
The Json itself
[{"title":"title1","url":"somefile1.pdf","background":"bg1.png"},
{"title":"title2","url":"somefile2.pdf","background":"bg2.png"},
{"title":"title3","url":"somefile3.pdf","background":"bg3.png"}]
Now how would I query the array to ensure only unique entries are being added?
Heres the code to add to array with
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'title': title,
'url': url,
'background': background
};
// Need to check the newItem is unique here //
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
I thought I could use the jquery unique function instead before setting the localstorage object
var cleanedItems = $.unique(oldItems);
localStorage.setItem('itemsArray', JSON.stringify(cleanedItems));
but that didnt work...
You will have to loop over each of the items in the array that is parsed from local storage and perform an object equality test with the new item.
Object equality testing is not as simple as obj1 == obj2.
Here are some references to get you started
http://procbits.com/2012/01/19/comparing-two-javascript-objects
https://github.com/joyent/node/blob/e4cef1a0833e6d677298600e205a142d15639bf2/lib/assert.js#L205-L247
http://stamat.wordpress.com/2013/06/22/javascript-object-comparison/
http://underscorejs.org/docs/underscore.html#section-84
The following may end up working for you, by using JSON.stringify to compare the new object as a JSON string with the objects in the old array as JSON strings.
function objInArr(newObj, oldItems) {
var newObjJSON = JSON.stringify(newObj);
for (var i = 0, l = oldItems.length; i < l; i++) {
if (JSON.stringify(oldItems[i]) === newObjJSON) {
return true;
}
}
return false;
}
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'title': title,
'url': url,
'background': background
};
// Need to check the newItem is unique here
if (!objInArr(newItem, oldItems)) {
oldItems.push(newItem);
}
localStorage.setItem('itemsArray', JSON.stringify(oldItems));

Categories