Storing multiple ID's in localStorage using JavaScript - javascript

I am wanting to add a favorites function for my website. The technologies I am using are html, css, javascript and json. I am loading the json file thru ajax. A user is able to search for a device and add that device to their favourites and that is done via sessionStorage and localStorage, but my problem is when a user clicks on a new phone to add to their favorite, it overrides it. Do I have to put like an IF statement which will say if there is an id there still add this one. I am confused on how to do this...
Code Samples....
$(document).on('click', '.productfavourite', function(event) {
// whichever HTML element has been clicked,
// grab the id of that and set it as product fave
productFave = event.target.id;
localStorage.setItem('productFave', productFave);
console.log(productFave);
window.location="favourites.html";
});

I would suggest you save the selected items in an object or array before you write it in to the localStorage. After that you convert the object or array to a json string.
var selected = [];
$(document).on('click', '.productfavourite', function(event) {
selected.push(event.target.id);
console.log(selected);
});
this returns an array that your can convert to json.
Hope this helps.

So what you need is to keep a collection (list or dictionary) containing the favorites. I'll give you some examples, then you can figure out the rest.
You get the current productFav in your localStorage as follows:
var fav = localStorage.getItem("productFav") || [];
Now you don't want to store one value in localStorage, you want your whole list there. So you add the new favorites to the list and serialize the result as a json string
fav.push(newItem);
localstorage.setitem("productfav", JSON.stringify(fav));
I assumed fav is a list. It's best to use a dictionary if you want to avoid adding duplicated entries

You can also try:
if(Storage !== "undefined") {
localStorage.setItem("productFave", localStorage.getItem("productFave")+ ", newItemValue3");
}

Related

Looping through array to store string values in objects in localStorage and retrieving them

I'm building a web app that lets the user curate a double-feature film showing. The user enters a title, a blurb, and two film titles. On a submit button a function is called that displays the user-submitted title, user-submitted blurb, and makes two separate API calls to retrieve movie information on each respective feature.
I'm trying to establish something of a favorites functionality that utilizes localStorage. Conceptualizing the solution, let alone implementing it may be my first mistake, so I'm open to alternative suggestions, but I believe the best way to do this is to capture each search field value (title, blurb, movie_1, movie_2), store these four string values in an object and then push that object to an array, placing each object into localStorage and then getting each object from localStorage later on with a button click.
I'm able to capture these items, store them in localStorage and dynamically generate buttons that when clicked populates the four search field values back into the respective search fields, allowing the user to click the submit button again which runs the api calls and displays all of the content (again: title, blurb, movie_1, movie_2).
My problem is looping through the objects and grabbing the different search field data values. I suppose the problem is in assigning a name or key to the different objects that I'm looping through in the array and then accessing the correct values from the appropriate button through localStorage. I seem to be setting the same localStorage object (or rewriting it) and accessing it over and over, as opposed to setting a new localStorage object and getItem'ing the right one.
I'll provide some code snippets below, but it might be easier to peruse my GitHub repo: https://github.com/mchellagnarls/double_feature
If you look at the repo, latest code is found in index_test.html and app_test.js, whereas a previous version without any of the broken favorite functionality is found in index.html and app.js.
Some code snippets:
// logic to capture search field values and to eventually display them as buttons
// empty array
var dfArray = [];
// object to hold each of the string values to populate the search fields
var doubleFeature = {
feature_1: movie_1,
feature_2: movie_2,
DFTitle: title,
DFBlurb: blurb
}
dfArray.push(doubleFeature);
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var savedDF = JSON.parse(localStorage.getItem("df"));
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})
Thanks for any help. I'm learning web development and I may be overcomplicating things or missing out on an easier way to think about it and/or solve it.
Instead of this loop:
for (var i = 0; i < dfArray.length; i++) {
localStorage.setItem("df", JSON.stringify(dfArray[i]));
var button = $("<button>");
button.addClass("df-favorite-button");
button.text(title);
$("#buttons-view").append(button);
}
I would place the whole array into local storage
localStorage.setItem("df", JSON.stringify(dfArray));
Also then you have to decide which object to get from array in click function
$(document).on("click", ".df-favorite-button", function() {
event.preventDefault();
var id = -1; // which one
var savedDF = (JSON.parse(localStorage.getItem("df")) || []).find(pr => pr.id === id);
$("#movie-input-1").val(savedDF.feature_1);
$("#movie-input-2").val(savedDF.feature_2);
$("#df-title-input").val(savedDF.DFTitle);
$("#df-blurb-input").val(savedDF.DFBlurb);
})

Recover displayed JSON data from webpage?

I have made a webpage on JSFiddle that can display a simple JSON string. I plan on implementing ways to add/edit/remove keys and values, which is what the buttons on the right are for. Before adding all that, how do I go from this webpage representation back to a JSON string with the same formating when I click 'Save'?
Do I need to tag each element specifically some how and do a forEach(element) and extract the text value and then..?
Code on JSFiddle
<script>
var new_json = {"RegEx":{}}
var keys = document.getElementsByClassName("json_header")
for (key in keys){
//Somehow extract key value that is displayed, add to new_json as a key.
// for each key, need to add each value.
for (value in values){?}
}
Somehow I need to know which values belong to which key, is this possible with parent/child associaton?
In the JSFiddle, I append all the values as children to the key value
New to HTML and Javascript, any other suggestions are welcome.
Thank you!

how to send variable value from one page to another

I am trying to send an information from one page to another through javascript file
the information will only contain a value of single variable.
how to accomplish this?I dont want to send it through query string as the value will be visible in the URL.
is there any other way?
You could save your data in LocalStorage and retrieve it on the other page.
localStorage.yourData = '{ test:"data" }';
console.log(localStorage['yourData']);
You have a few options to do that.
Depending on what browser is used, using localStorage is an option
//localStorage ONLY stores flat key:value pairs and can't contain Objects
localStorage.myString = "hello world";
localStorage.myObject = JSON.stringify({ foo: "bar" });
//Reading back the values is simple aswell
var myString = localStorage.myString;
var myObject = JSON.parse(localStorage.myObject);
Another method would be using a hash or query string. For example, you could redirect to www.yourdomain.com/your/path?myValue=1234
And then parse that by reading the search value from window.location.search (Will return ?myValue=1234 in that case) and splitting it on =:
var myValue = window.location.search.split("=")[1];
Another option is using hashes, similar to query params. Or even cookies.
BUT, all these methods will expose the value to the user, so if he wants to get that value, he will be able to!
At first, as other answers, use localStorage or sessionStorage to store global data.
Otherwise, you can add an event listener to detect the change of the storage value in your target page as follow:
window.addEventListener('storage', (e) => console.log(e.key, e.oldValue, e.newValue))
See: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent

Passing values from a page to another page in HTML mobile app

I've made users to enter some values in a html page:
Here is the code:
$(function() {
$("#savesymptoms").bind(
"click",
function() {
var url = "notes.html?acne="
+ encodeURIComponent($("#acne").val())
+ "&back="
+ encodeURIComponent($("#bloat").val());
window.location.href = url;
});
});
And I've added an alert like this:
alert("values passed");
But I'm not sure that this is working. I've got some 10 values to pass to another page. Above code contains only two values. Can I use arrays to pass all 10 values? I don't want to use nomenclature used in my code, i.e., individual value passing.
P.S: acne and bloat are the ids of the fields where user enters the data. notes.html is the page where I want to pass the data.
In my opinion you can use sessionStorage in HTML5
For setting a value
sessionStorage.setItem('name', 'value');
For getting the value:
sessionStorage.getItem('name');
if you want to store the value permanently use localStorage.
Since you have almost 10 values push all those values in a JSON and store it either in sessionStorage/localStorage.
You can retrieve it else where and use as per your wish
Note:values stored will be in the form of string even if you push it as JSON.You will have to make it to JSON using Jquery functions
Alternative
You can store it as window.name
But this will be only valid till the window lasts/tab closed(same as sessionStorage)

Correct way to model a collection of items in Firebase

In the docs I see a lot of examples using index values as a part of the key name for a particular item --- but I don't understand how this is a consistent way to model your data.
For example let's say I have a list of articles:
https://gigablox.firebaseio.com/articles/
article1
article2
article3
When I'm ready to add article4 I know I can use:
var length = Object.keys($scope.articles).length;
And using AngularFire 0.5.0 I can save it with:
var name = 'article' + length + 1;
$scope.articles[name] = $scope.article;
$scope.articles.$save(name);
But what happens if I:
$scope.articles.$remove('article2');
And add another record using the same approach? We're likely to create duplicate key names.
To add a little complexity, let's add a single relationship and say that each article has comments.
What is the correct way to model this data in a Firebase collection?
Please use $add and let Firebase automatically generate chronologically ordered lists for you.
var ref = new Firebase("https://gigablox.firebaseio.com/articles/");
$scope.articles = $firebase(ref);
$scope.addArticle = function() {
$scope.articles.$add($scope.article);
}
$scope.removeArticle = function(id) {
$scope.articles.$remove(id);
}
Firebase automatically creates key names when you call $add. You can iterate over the key names using ng-repeat:
<div ng-repeat="(key, article) in articles">
<div ng-model="article"><a ng-click="removeArticle(key)">Remove</a></div>
</div>
EDIT: You should follow the suggestion from #Anant if you want an array-based collection.
However, for this specific scenario as outlined by #Dan Kanze, if you want to pull the key out of the URL (as would be done for a content management system, etc), you should generate your own keys unique to the content. For example, if you know that article names need to be unique, create a slug function that will:
Lowercase the article name
Replace spaces with underscores
etc..
If the article name changes, you would not delete the old entry. Instead, create a new entry in Firebase and use the old key to point to the new location for 301 redirects, etc.

Categories

Resources