Adding Items to an Empty Array with Javascript - javascript

I'm just learning Javascript and need to build a cart.
I am using a drop-down menu to select the items which are stored in another array. I then want to push the selected item to an empty array called "cart"
This is the code I'm using to select the data from the catalog array inorder to push it to the cart array:
let addFCat = document.getElementById('addfromCat');
function cat_Cart(){
// find out the index of the item loaded
let e = document.getElementById("productList");
let itemIndex = e.options[e.selectedIndex].value;
console.log(itemIndex);
// update item to cart
cart.push(catalog[itemIndex]);
localStorage.setItem("cart", JSON.stringify(cart));
// alert with updated total
// alert(`You added ${cartItems.name} to your Cart`)
}
But for some reason my cart[] remains empty.
If I manually type:
cart.push(catalog[enter index here]) in the console,
and then:
cart.length;
the cart updates.
What am I doing wrong, that it won't update my cart within the function?
(PS. I'm using the console.logs to check the code is running)

I think it is because you do refresh your browser, and it causes your cart[] to be empty, I suggest you to store the cart array in empty condition, to localStorage first, and get the updated value like this
const cart = []
localStorage.setItem("cart", JSON.stringify(cart));
function cat_Cart(){
const getCart = JSON.parse(localStorage.getItem("cart"));
// find out the index of the item loaded
let e = document.getElementById("productList");
let itemIndex = e.options[e.selectedIndex].value;
console.log(itemIndex);
// update item to cart
getCart.push(catalog[itemIndex]);
localStorage.setItem("cart", JSON.stringify(getCart));
// alert with updated total
// alert(`You added ${cartItems.name} to your Cart`)
}
local storage will help you to save any data, and it will not to be deleted even though you refresh the browser. thank you

Related

Problem conditions if and else if in a for loop adding quantity in object in array or new object in array not working why?

my problem is that in my if and else if condition of the for loop the first condition is triggered if we add the second same product contained in the table but when the color condition of the product changes and that lid and the same it triggers me two conditions for the click on the product. What to do ?
I would like to add a quantity ++ if the object and already in the table if the id and the color selected in the input are the same.
otherwise you add a new object in the table.
After the problem is that it adds both the quantity in the product and the quantity in the object here is my code and some screenshot of the console below
produitData = product choice on the page of product
produitTableau = Array an objects save in the localStorage
select = the input contained the varnish value
const addBasket = () => {
let bouton = document.getElementById(produitData._id);
bouton.addEventListener("click", () => {
let produitTableau = JSON.parse(localStorage.getItem("produit"));
let select = document.getElementById("vernis");
const fusionProduitTeinte = Object.assign({}, produitData, {
teinte: `${select.value}`,
quantite: 1,
});
if (produitTableau == null) {
produitTableau = [];
produitTableau.push(fusionProduitTeinte);
localStorage.setItem("produit", JSON.stringify(produitTableau));
} else {
for (i = 0; i < produitTableau.length; i++) {
if (
produitTableau[i]._id == produitData._id &&
produitTableau[i].teinte == select.value
) {
produitTableau[i].quantite++;
console.log("quantite ++");
localStorage.setItem("produit", JSON.stringify(produitTableau));
} else {
console.log("nouveau");
produitTableau.push(fusionProduitTeinte);
localStorage.setItem("produit", JSON.stringify(produitTableau));
}
}
}
console.log(select.value);
console.log(produitTableau);
// window.location = "panier.html";
});
return;
};
one click one object add to array
second click quantity++ add in object to the array it's work the fisrt conditions
enter image description here
third click quantity++ add in object to the array it's work the fisrt conditions
enter image description here
four click im changed the select value
but the product id is the same as in the object in the table quantity++ add in object to the array and new object for the same time it's not work conditions and continue to add new object in the array for the different value and add quantity++ in the infinity
enter image description here
what's the solution is for the good conditions in my code function?

delete specific element in an array of local storage

Currently I have datas variable that contains multiple element values.
like this
["WLP001","WLP002","WLP003","WLP004","WLP022"]
Deleting datas variable will be possible like this localStorage.removeItem("datas");
But if I have a variable in my js code like this var item = "WLP022";
and delete only the WLP022 inside of that datas would it be possible?
You can get index of item to delete then just use splice to remove that item from array and set your datas again in localStorage.
Demo Code :
var to_delete = "WLP003"
//var datas = localStorage.getItem('datas');//parse it
//suppose this is data
var datas = ["WLP001", "WLP002", "WLP003", "WLP004", "WLP022"];
var index = datas.indexOf(to_delete);//get index
datas.splice(index, 1);//remove it
console.log(datas)
localStorage.setItem('datas', JSON.stringify(datas));//set again

How to get localStorage item count (by value) into a local variable?

Whenever I load a page which holds a different url name at the end, I set up a localStorage item, which holds the value activeGameSession:
var pageUrl = window.location.href,
pageUrlParts = pageUrl.split("/"),
gameUrl = pageUrlParts[pageUrlParts.length-1],
activeGames = [];
if (gameArea.length) {
var gameList = Object.values(localStorage);
localStorage.setItem('game_' + gameUrl, 'activeGameSession');
for (var i = 0; i < gameList.length; i++) {
if (gameList[i] === 'activeGameSession') {
activeGames.push(gameList[i]);
}
}
}
In the Application tab of my browser, it clearly shows that I have 2 items with that value in my localStorage, but when I log the activeGames array in my console, it says that I have only 1 item in my array.
e.g. When I get 1 item in my array, and load another page, it should add one more active item to my local array, just as localStorage holds 2 items, but it does not, it only adds 1.
console.log(activeGames);
["active"]
When I should have:
console.log(activeGames);
["active", "active"]
Why is this happening, and how can I bypass this issue?

Delete specific string from Local Storage array

I have this code
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
let deleted = moment.splice(index, 1);
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
}
I have found the index of the element of the array that I want to delete, everything's good, but now I would like to "update" the local storage to delete the item from the index.
I can delete the specific value on the array that loads into the local Storage. Called myArray.
const myArray = map(listItems, getText);
myArray contains the "raw string data" that then gets put on the local Storage via,
localStorage.setItem('things',JSON.stringify(myArray));
How can I delete from the localStorage?
I've tried, the splice method on the local storage but doesn't work!!
Thanks!
try to parsing the moment variable to JSON
using
edit
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
//try to add this code
let moment_parse = JSON.parse(moment);
let deleted = moment_parse.splice(index, 1);//edit
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
before you splice the moment variable
The problem is that you've made a mistake using Array.splice.
This method mutates the given array.
You don't need the result of the splice operation. Instead you must pass the array as the new value to update the localstorage.
// 1. read value
const moment = JSON.parse(localStorage.getItem('pelis_guardades'))
// 2. mutate given array by removing one element from index.
moment.splice(index, 1);
// 3. write value
localStorage.setItem('pelis_guardades', JSON.stringify(moment))

index value cannot updated

Here I am using array to store date in local-storage. first add data that is stored after add another one the index value not increased. The newly add data only shows.
function save() {
var task = [];
localStorage.getItem('task');
task.push(document.getElementById("txt1").value);
console.log(task);
localStorage.setItem('array', task);
}

Categories

Resources