Cherenkov
Cherenkov

Reputation: 495

How to store multiple items on Local Storage when a button is clicked?

I'm trying to store multiple items based on this function:

onclick="s(iId)"

This is the function that I'm using:

function s(i_id) {
    var items = [];
    items.push(i_id);
    localStorage.setItem("i", JSON.stringify(i));
}

The problem is that it is only storing one id when the button is clicked and refreshed every time is clicked. How can I make it store multiple ids?

Upvotes: 5

Views: 30023

Answers (2)

István
István

Reputation: 5127

You have to call the onclick like this:

onclick="store([itemId1, itemId2, itemId3])"

and the function:

function store(item_ids) {
    var items = [];
    for(var i = 0; i < item_ids.length; i++) {
        items.push(item_ids[i]);
    }
    localStorage.setItem("item", JSON.stringify(items));
}

Considering if you want to add new array to storage on every click...

Upvotes: 0

GMchris
GMchris

Reputation: 5648

The problem is, you're creating a new array, pushing a single id in it, and then saving it every time the function is called. Two things you could do is move the items array outside of the function, and simply push to it, before saving them. The second option is, getting the already stored value, parsing it with JSON.parse and pushing a new item in it, before saving it again.

I suggest going with option 1, even if it creates a global variable. It's much faster.

var items = [];

function store(item_id) {
    items.push(item_id);
    localStorage.setItem("item", JSON.stringify(items));
}

Upvotes: 9

Related Questions