i have 5 items in my page with 3 information. (for example, name and price and number )
i want when i click on them (for example item 1) for first time, create an object and save items information to localStorage and for another times increase the number of item in localstorage.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let exist = localStorage.getItem('name');
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
localStorage.setItem('name', name);
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
localStorage.setItem('price', price);
var number = localStorage.getItem('number');
number = parseInt(number);
if (number) {
localStorage.setItem('number', number + 1);
} else {
localStorage.setItem('number', 1)
}
});
});
})();
its my code, but when i click on any item, previeos details in localstorage will be lost and information of new item replaced.
how i can resolve it?
When you are calling localStorage.setItem('name', name) you are overwriting the previous value of name. To store all names, prices, and numbers you have to use array. But, localStorage supports nothing but string. So before writing, you have to convert the array to a string, and upon reading you have to revert the string back to an array.
function() {
items.forEach(function(btn) {
btn.addEventListener('click', function(event) {
let names = localStorage.getItem('name');
const exists = !!names;
names = exists ? JSON.parse(names) : [];
let prices = exists ? JSON.parse(localStorage.getItem('price')): [];
let numbers = exists ? JSON.parse(localStorage.getItem('number')) : [];
var name =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[0].textContent;
const nI = names.indexOf(name);
if (nI === -1) {
names.push(name);
localStorage.setItem('name', JSON.stringify(names));
var price =
event.target.parentElement.parentElement.parentElement.parentElement.children[1].children[2].textContent;
prices.push(price);
localStorage.setItem('price', JSON.stringify(prices));
numbers.push(1);
} else {
// else they are already in localStorage, just increase number
numbers[nI]++;
}
localStorage.setItem('number', JSON.stringify(numbers));
});
});
})();
Related
I wanted to save data in local storage in form of array.
the first item is adding successfully but when i try to ad second item it replace item 1
this is my script file
function store(title, description) {
let titl = JSON.parse(localStorage.getItem("titl"));
let descriptio = JSON.parse(localStorage.getItem("descriptio"));
if (titl == null) {
t = [title];
localStorage.setItem("titl", JSON.stringify(t));
} else {
t = [title]
titl.push(t);
}
if (descriptio == null) {
d = [description];
localStorage.setItem("descriptio", JSON.stringify(d));
} else {
d = [description];
titl.push(d);
}
}
you dont update localstorage for the second values, and your pushing an array with a value onto an array (i think you just want to push a value onto the array)?
I think something like this is what your trying to acheive?
function store(title, description) {
// load the existing values (default to an empty array if not exist)
let _title = JSON.parse(localStorage.getItem("title") || "[]")
let _description = JSON.parse(localStorage.getItem("description") || "[]")
// add the new items
_title.push(title)
_description.push(description)
// update stored values
localStorage.setItem("title", JSON.stringify(_title)
localStorage.setItem("description", JSON.stringify(_description)
}
so basically i want to make a phone contacts app, and i try to save the saved contact to local storage
so this is the function when the save button clicked
saveContact(name, number){
//To check if the name input or phone input is not blank
if(nameInput.value == '' || phoneInput.value == ''){
info.style.display = 'block'
}
const firstLetter = name[0].toUpperCase()
const getContact = localStorage.getItem(firstLetter)
const storedObject = {
[name]:number
}
//If contact's first letter exists in localstorage
if (getContact){
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
oldData.push([storedObject])
const oldDataString = JSON.stringify(oldData)
localStorage.setItem(firstLetter, oldDataString)
const finalOldData = []
//i do a looping here to push each contact's object to a new array which is finalOldData
//but it doesn't work well. it doesn't actually add a new object to the array instead of replacing the old object with a new one
oldData.forEach(e => {
finalOldData.push(e[0])
})
const finalOldDataString = JSON.stringify(finalOldData)
localStorage.setItem(firstLetter, finalOldDataString)
}
//If contact's first letter doesn't exist in localstorage
else{
const storedObjectString = JSON.stringify([storedObject])
localStorage.setItem(firstLetter, storedObjectString)
this.clearSave()
}
}
so the issue is when i try to add a contact which its first letter exist in local storage and make it as a list
//and this is the result i want
Storage
A: "[{\"amber\":\"1242134\"},{\"annie\":\"123421\"}]"
length: 1
You can consider the code below, it is working as expected.
Changes
const oldData = [JSON.parse(localStorage.getItem(firstLetter))]
No need to put the result from JSON.parse into an array, it already is an array and also you can use the variable getContact instead of calling getItem again on localStorage.
oldData.push([storedObject])
No need to push an array into oldData, simply push storedObject.
I've removed the initial check for making testing easy, you can add it back.
function saveContact(name, number) {
if (!name || !number) {
return;
}
const firstLetter = name[0].toUpperCase();
const getContact = localStorage.getItem(firstLetter);
const storedObject = { [name]: number };
if (getContact) {
const oldData = JSON.parse(getContact);
oldData.push(storedObject);
const oldDataString = JSON.stringify(oldData);
localStorage.setItem(firstLetter, oldDataString);
} else {
const storedObjectString = JSON.stringify([storedObject]);
localStorage.setItem(firstLetter, storedObjectString);
}
}
I want to add objects into a local storage array if they are not in it otherwise, increase the objects' quantity by 1. Here is my function:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (productsTable === null){
// If not, initialize the array and add the current object
productsTable = [];
objetProduit.quantity ++;
productsTable.push(objetProduit);
}else{
// If yes, decode the array.
productsTable = JSON.parse(productsTable);
// check if the object is already in the array
if(productsTable.find(product => product.id !== objetProduit.id)){
//if not ==> add the object into the array
objetProduit.quantity ++;
productsTable.push(objetProduit);
}else if (productsTable.find(product => product.id == objetProduit.id)){
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity ++;
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
The objetcs are instances of the class below :
class Appareil {
constructor(id,name,price,description,imageURL, quantity){
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.imageURL = imageURL;
this.quantity = quantity;
}
}
The array get initialized but items are not added in it nor is the quantity modified.
Avoid the following check condition:
if(productsTable.find(product => product.id !== objetProduit.id))
as it will return the first product's index which doesn't match in the array, so chances are there will be many products which will not be matching
Refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Try:
function addToCart() {
let productsTable = localStorage.getItem("productList");
// Check if productsTable exists in local storage
if (!productsTable) {
// If not, initialize the array and add the current object
productsTable = [];
objetProduit.quantity++;
productsTable.push(objetProduit);
} else {
// If yes, decode the array.
productsTable = JSON.parse(productsTable);
// check if the object is already in the array
if (productsTable.find(product => product.id === objetProduit.id)) {
//if yes ==> just increase the value of the key quantity by 1
objetProduit.quantity++;
for (var i = 0; i < productsTable.length; i++) {
if (objetProduit.id === productsTable[i].id) { //look for match with id
productsTable[i].quantity++; //add
break; //exit loop
}
}
} else {
//if not ==> add the object into the array
objetProduit.quantity++;
productsTable.push(objetProduit);
}
}
// Encode the array.
productsTable = JSON.stringify(productsTable);
// Add the array back to LocalStorage.
localStorage.setItem("productList", productsTable);
}
I am new to JSON, so bear with me!
I am working on a website that stores values to LocalStorage via inputs. Each form input has the following function (only difference is formInput2, formInput3)
function formInput(e) {
// Save userInput from input
// Get form values
var input = document.querySelector('.input').value;
this.style.visibility = 'hidden';
smtBtn.style.display = 'inline-block'
var userInput = {
answer: input
}
// Test if bookmark is null
if (localStorage.getItem('bookmarks') === null) {
// Init Array
var bookmarks = [];
// Add to array
bookmarks.push(userInput);
// Set to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
} else {
// Get Bookmarks from LocalStorage
var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
// Add bookmark to array
bookmarks.push(userInput);
// Reset back to LocalStorage
localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
}
// Refetch bookmarks
fetchBookmarks();
// Prevent form from submitting
e.preventDefault();
}
I need to add the three numbers that are in local storage, and I am using this function:
function bookmarkMath() {
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
for (i = 0; i < bm1.length; i++) {
total += bm1[i].answers;
}
console.log(total);
}
}
But alas, my output is NaN. :(
Any help would be very appreciated!!!!!!!
edit: In dev tools, this is what I get back with console.log(LocalStorage) - the numbers I have entered in the form on the site.
Storage {bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]", length: 1}
bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]"
length: 1
__proto__: Storage
Edit 2: I have updated the second ]function to include the JSON.parse. But now I am getting just the numbers 0245 as my result, NOT the sum of 0+2+4+5. Any help?? :p
You are on the right track by doing JSON.parse(). However, the value is in a string. You can see quote at the value it is mean will be threated as a string. You should convert it to number format like following:
total += parseInt(bm1[i].answers);
If you don't want to do parseInt() then your output should be :
{"answer": 2} //this one mean your value is Number
Instead:
{"answer":"2"} //this one mean your value is in String
I think I see it ... this statement looks "wrong, yet something that JavaScript would accept!"
var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
total = 0,
i;
Notice the commas.
Instead, write this as three separate lines:
var var bm1 = JSON.parse(localStorage.getItem('bookmarks'));
var total = 0;
var i;
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || []
const totalAnswers = bookmarks.map(o => +o.answer).reduce((a, b) => a + b)
I need a javascript array or object or maybe something mixed for this task:
I have this attributes:
customer
item
barcode
So I will fill all fields with loop like this:
customer = 1
item = 1
barcode = 5555
customer = 1
item = 2
barcode = 6666
the combination of customer and item will be unique, so I want to directly access the value (barcode), like this:
"give me the barcode value where customer = 1 and item 1, so the result must be 5555"
I don't want to use loop to find the value, I want direct access.
Thanks!
Currently, I have created example script. My question is there anything better?
function cacheBarcodes() {
var results = [];
// Here the database is pushing all 100k+ records to the array
results.push(['1', '1', '5555']);
results.push(['1', '2', '6666']);
return results;
}
function getBarcode(results,customer,item) {
for (var i = 0; i < results.length; i++) {
var db_customer = results[i][0];
var db_item = results[i][1];
var db_barcode = results[i][2];
if (db_customer == customer && db_item == item ) {
return db_barcode;
}
}
}
results = cacheBarcodes();
alert(getBarcode(results,'1','1'));
First off, need to get the most important thing out of the way: this is a terrible idea. Don't actually do this unless you are way beyond sure that you need to:
var salt = "___";
var genKey = function(r) {
return '' + r.customer + salt + r.item;
};
var barcodes = {};
records.forEach(function(r) {
var key = genKey(r);
barcodes[key] = r.barcode;
});
Now you can call genKey with the record to access the barcode for the cost of a function call and hash lookup instead of looping through the array of records. As Anirudha pointed out in the comments you probably gain nothing by this. It gets a little better (in terms of cleanliness, not performance) if you put an interface on it:
class Lookup {
constructor () {
this._barcodes = {};
}
_genKey (customer, item) {
return '' + customer + '___' + item;
}
addRecord (r) {
let key = this._genKey(r.customer, r.item);
this._barcodes[key] = r.barcode;
return this;
}
getBarcode (customer, item) {
let key = this._genKey(customer, item);
return this._barcodes[key];
}
};