Can't Get Info From Localstorage - JavaScript - javascript

I'm learning how to use localstorage in JavaScript, so I made an application to get some practice. When I ran the code it gave me this error:
I put the html and css on a codepen, here is the link:
Link To Code
JavaScript Code
// READY
$(document).ready(() => {
// when user clicks on submit
$(".submit").on("click", addItem);
// show bookmarks
showBookmarks();
})
// ADD ITEM
let addItem = (e) => {
// get values from inputs
let name = $(".name").val();
let link = $(".url").val();
// stores bookmarks
let bookmark = {
name: name,
url: link
};
// bookmark varification
// if theres nothing in bookmarks
if(localStorage.getItem("bookmarks") == null) {
// init array
let bookmarks = [];
// add to array
bookmarks.push(bookmark);
// set to local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
} else { // if theres something in bookmarks
// get from local storage
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// add bookmark to array
bookmarks.push(bookmark);
// reset back to local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
// prevent form from submitting
e.preventDefault();
}
// SHOW BOOKMARKS
let showBookmarks = () => {
// get from local storage
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// loop through local storage data
for(let i = 0; i < bookmarks.length; i++) {
let name = bookmarks.name[i];
let url = bookmarks.url[i];
// append bookmarks
$(".show").append(`
<div class="bookmarks-container">
<div class="bookmark">
${name}
<i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
</div>
`);
}
}
// DELETE ITEM

I figured it out. I had to change:
for(let i = 0; i < bookmarks.length; i++) {
let name = bookmarks.name[i];
let url = bookmarks.url[i];
to:
for(let i = 0; i < bookmarks.length; i++) {
let name = bookmarks[i].name;
let url = bookmarks[i].url;
This is because I was cycling through name and url but, I'm tell the browser at the start of my for loop to cycle through bookmarks.

Try this:
let bookmarks = localStorage.getItem("bookmarks") !== null ? JSON.parse(localStorage.getItem("bookmarks")) : [];

You are calling the showBookmarks method on load which then tries to parse the localStorage "bookmarks" item. That value is undefined when it tries to loop through it and undefined has no length.
if(!bookmarks){
return;
}
Here is the example working

Related

How to keep array of objects in localstorage

i'm trying to use localstorage for my array of objects but it doesn't work (without the localstorage it works perfectly). after a few days of tries i'm trying here. can anyone help please?
The Code:
<script>
var notes = JSON.parse(localstorage.getitem("notes") || "[]");
function todo() { // Gets invoked by a submit button
var list = document.getElementById("tasklist").value;
var taskdate = document.getElementById("taskdate").value;
var tasktime = document.getElementById("tasktime").value;
const note = {
list: list,
taskdate: taskdate,
tasktime: tasktime
}
notes.push(note);
for (i = 0; i < notes.length; i++) {
document.getElementById("name").append(notes[i].list);
}
localStorage.setItem("notes", JSON.stringify(notes));
}
</script>
You have used incorrect keyword.
localstorage => localStorage
getitem => getItem
Your code seems valid except for some syntax errors. Use a good IDE or code editor or whatever to show you that errors. I recommend vscode
var notes = JSON.parse(localStorage.getItem("notes") || "[]");
function todo() { // Gets invoked by a submit button
var list = document.getElementById("tasklist").value;
var taskdate = document.getElementById("taskdate").value;
var tasktime = document.getElementById("tasktime").value;
const note = {
list: list,
taskdate: taskdate,
tasktime: tasktime
};
notes.push(note);
for (let i = 0; i < notes.length; i++) {
document.getElementById("name").append(notes[i].list);
}
localStorage.setItem("notes", JSON.stringify(notes));
}
try please declare as array, note variable
var note = array();
note = {
list: list,
taskdate: taskdate,
tasktime: tasktime
}

Add items to basket and store in localStorage with JavaScript

I want to create an action for the button to be able to add items to the basket and keep data in localStorage. I'm struggling with push items when the basket has already more than one item inside. I can easily increase the quantity of existing items if an ID is same but can't add new items. Data I'm getting from JSON file. JSON contains only five unique IDs. Below part of my code.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
const basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if(basket === undefined || basket.length > 4 ){
//Existing data block in local storage
basket.forEach(product => {
if (product.elementId === elementId) {
product.elementQuantity++
console.log('increase');
}
});
} else{
//Non Exist data block in local storage
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
console.log('add')
window.location.reload();
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Here is a working solution for your problem.
AddBtn.addEventListener('click', function (add) { //Add item to when click AddBtn localStorage
add.preventDefault() // Avoid default action.
let basket = JSON.parse(localStorage.getItem('basket')); // Parse data from localstorage
let elementimageUrl = element.imageUrl; // element.imageUrl is a part of backend data received from JSON file
let elementId = element._id; // element._id is a part of backend data received from JSON file
let elementName = element.name; // element.name is a part of backend data received from JSON file
let elementPrice = element.price; // element.price is a part of backend data received from JSON file
let elementQuantity = 1;
if (!basket) {
basket = [];
}
// find the index of the item if already in basket
const itemIndexInBasket = basket.findIndex(basketEntry => basketEntry.elementId === elementId);
if (itemIndexInBasket !== -1) {
basket[itemIndexInBasket].elementQuantity++;
} else {
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl}); // Push not existing data to localstorage
}
localStorage.setItem('basket', JSON.stringify(basket));
});
Can you share a jsfiddle link with dummy values for variables? It will be a lot easier to debug.
Seeing the above explanation that you are facing a problem with push items I assumed this below data and it is working.
const basket = [{abc:"1"},{abcs:'3'}];
let elementimageUrl = 'abc';
let elementId = 1;
let elementName = 'a';
let elementPrice = 10;
let elementQuantity = 1;
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl});
console.log('add')
console.log(basket);
localStorage.setItem('basket', JSON.stringify(basket));

How to locally store (JS) a HTML button and retrieve the button/s on page load

I am wanting some help with this project I am working on. The part needed for this question is that the user creates a button and then can click on it to update parts of the page based on the id (created from the user input) of that button. This works.
However, I want to be able to save and retrieve these buttons using localStorage. I have worked with localStorage before, but nothing I try seems to work. Is it even possible to store HTML elements locally?
Just looking for some clarification of how I should go about this, or an example.
Thanks, Elliot.
on page load:
if (typeof(Storage) !== "undefined") {
let groupsLoaded = localStorage.getItem("storedGroupArray");
$("#createdGroups").prepend(groupsLoaded);
}
when creating and (hopefully) storing buttons:
let groupArray = [];
function addGroup() {
let userInput = $("#groupName").val();
if(userInput.length >= 1) {
let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
$("#createdGroups").append(newGroup);
groupArray.unshift(newGroup);
let groups = localStorage.setItem("storedGroupArray", userInput);
$("#groupName").val("");
} else {
alert("Please enter a group name.")
}
};
LINK TO CODE SO FAR:
https://codepen.io/elliot7-7/pen/zYvrBWy
(Ignore the task sections)
I would store an array of created group names in localStorage.
Later on they can be retrieved and processed as html elements with specified template.
let groupArray = [];
let groupNames = [];
function addGroup() {
let userInput = $("#groupName").val();
if(userInput.length >= 1) {
let newGroup = $(`<button id='${userInput}' class='createdGroupsButton'>${userInput}</button>`);
$("#createdGroups").append(newGroup);
groupArray.unshift(newGroup);
groupNames = [...groupNames, userInput];
localStorage.setItem("storedGroupArray", JSON.stringify(groupNames));
$("#groupName").val("");
} else {
alert("Please enter a group name.")
}
};
if (typeof(Storage) !== "undefined") {
let storedGroupNames = JSON.parse(localStorage.getItem("storedGroupArray"));
if(storedGroupNames) {
for(let groupName of storedGroupNames) {
let newGroup = $(`<button id='${groupName}' class='createdGroupsButton'>${groupName}</button>`);
$("#createdGroups").append(newGroup);
}
}
}

How to fetch localstorage data in different screen?

I am using Ionic and I am saving the preference of a user in localstorage.
Now, I would want to show this data in the profile of this person (so in a different screen / page), yet I have no clue how I should fetch this data.
Could someone help me out?
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
This is my Codepen:
https://codepen.io/CrocoDillon/pen/pIlKB
As long as you are staying on the same domain, you should have access to the same localStorage object. So this should work:
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
const favorites = JSON.parse(localStorage.getItem('favorites')) || [];
localStorage.getItem('favorites') itself is an accessor

Can't Delete Item From Localstorage - JavaScript

I've just started learning about localstorage in javascript, so I'm working on a project to practice. My program is a bookmark manager. The user can input a name and the url for there webpage, then it'll be stored and prepended to a div. If the user clicks on a trash icon, I want to find the url link that is associated with that trash icon, then remove it from localstorage.
Here's a link to the code and a demo.
LINK
JS
// READY
$(document).ready(() => {
// when user clicks on submit
$(".submit").on("click", addItem);
// when user clicks on delete
$(".fa-trash").on("click", deleteItem);
// show bookmarks
showBookmarks();
})
// ADD ITEM
let addItem = (e) => {
// get values from inputs
let name = $(".name").val();
let link = $(".url").val();
// stores bookmarks
let bookmark = {
name: name,
url: link
};
// bookmark varification
// if theres nothing in bookmarks
if(localStorage.getItem("bookmarks") == null) {
// init array
let bookmarks = [];
// add to array
bookmarks.push(bookmark);
// set to local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
} else { // if theres something in bookmarks
// get from local storage
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// add bookmark to array
bookmarks.push(bookmark);
// reset back to local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
}
}
// SHOW BOOKMARKS
let showBookmarks = () => {
// get from local storage
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// loop through local storage data
for(let i = 0; i < bookmarks.length; i++) {
let name = bookmarks[i].name;
let url = bookmarks[i].url;
// append bookmarks
$(".show").prepend(`
<div class="bookmark">
${name}
<i class="fa fa-trash fa-lg" aria-hidden="true"></i>
</div>
`);
}
}
// DELETE ITEM
let deleteItem = (url) => {
// get bookmarks from localstorage
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// loop through bookmarks
for(let i = 0; i < bookmarks.length; i++) {
if(bookmarks[i].url == url) {
// remove from array
bookmarks.splice(i, 1);
}
}
// reset local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
showBookmarks();
}
$(".fa-trash").on("click", deleteItem);
Should be
$(document).on("click", '.fa-fresh', deleteItem);
You are using the method for storing, not for removing. Your code should be like
localStorage.removeItem("bookmarks");
you can find more info here
You are never passing the url, but you can derive it from event object like this:
let deleteItem = (event) => {
// get bookmarks from localstorage
var a = $(event.target).siblings("a");
var url = $(a).attr("href");
let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
// loop through bookmarks
for(let i = 0; i < bookmarks.length; i++) {
if(bookmarks[i].url == url) {
// remove from array
console.log("removing i");
bookmarks.splice(i, 1);
}
}
// reset local storage
localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
showBookmarks();
}
Use this localStorage.removeItem(key);
I ran into an issue where localStorage.removeItem('myItem'); was not truly deleting the item.
I found that if I added
window. before actually solved the issue:
window.localStorage.removeItem('myItem');

Categories