Thanks for replying and yeah I’ll take care of the format of asking question next time. Also if i don’t use let accountlist = [ ], how can I save the “accountform” entries as many times I click button in local storage? I removed “let accountlist = [ ]” but it’s only saving one account form entry in local storage
I guess it depends on your needs, requirements and needs; there are multiple ways of doing it.
1 - since you’ve talked about clicking button I guess the starting point is listening to the event.
2 - Now it depends on your page/data/content but the general idea is to collect all the data you need first then add it into localStorage on the event handler.
Hope this clarify your ideas.
Feel free to post more details if you need further help
Let me explain my whole problem. I have a form “create account” with account number field, name field, balance field and I also have a button. Now I added a function create account code is below.
const addaccount = () => {
let accountlist = [];
let accountform = {
“accountno” : document.getElementById(“account”).value,
“custname” : document.getElementById(“name”).value,
“balance” : document.getElementById(“balance”).value
}
for(let i = 0; i < accountlist.length; i++){
accountlist.push(accountform);
}
localStorage.setItem(“Accountlist”, JSON.stringify(accountlist));
}
Now with your suggestion, I removed accountlist[ ] because for loop will not execute with empty array and then I added
Now it’s only saving one accountform entry in local storage but I want it to save as much accountform entries as I enter. For e.g if I add one entry “account input value”, “name input value”, “balance input value” it will save one entry and if i add another it will save that too without overwriting previous one. Hope now you can understand my problem.
Can someone explain why by putting empty array inside function, I can only add one account entry, if I add more it will overwrite the previous one but when I put empty array outside function, I’m able to add multiple account entries without overwriting previous entries.
Ideally don’t do this, store each account under an ID that you search for, seperately, because atm you’re making yourself something that is very error prone (see the difficulty you’re having saving these to an array). Local Storage is extremely basic in terms of what you can store and how you store it, and you need to make it as simple as possible, rather than needing multiple serialise/deserialise steps
Thankyou everyone for your help. @DanCouper yes, you’re right, localstorage is very simple in terms of what you can store but I was complicating it by storing and then retrieving and then changing value of it’s one stored object property. It was becoming really messy. Can you suggest another approach for my project. I’m dropping link here also I have another question jQuery in my project is working in codepen but not in browser.