Niek Nijland
Niek Nijland

Reputation: 772

Delete keys form localStorage with loop

I have a page where you can add and remove ingredients which will display in an unordered list. When the user clicks on "Find recipe!" the list items will be saved in separate keys in the localStorage.

enter image description here

Now I will delete the Carrot, Potato, Tomato and Chips and click on "Find Recipe!". Now the code will check how many li's are left and delete the rest.

var ingredients;
$('#findRecipe').click( function() {
    var i;
    for(i = 1; i <= $('#ulLeft li').length; i++) {
        ingredients = $('#ulLeft li:nth-child(' + i + ')').text();
        localStorage.setItem('ingredientsAvailable' + i, ingredients);
    }
    if(localStorage.key(i) !== null) {
        for(var j = i; j<=localStorage.length; j++ ) {
            localStorage.removeItem('ingredientsAvailable' + j);

        }
    }

});

But the code only deletes 2 keys in the localStorage. Doesn't matter how many I delete it only will delete 2 keys.

enter image description here

But when I do this a second time it WILL delete the right number. What's wrong with my code?

Upvotes: 2

Views: 1063

Answers (2)

Nathan Bubna
Nathan Bubna

Reputation: 6943

If you use https://github.com/nbubna/store then you can just do store.clear(); and let the library worry about getting it correct (which it does, of course).

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

When you remove an item, the length changes. You should iterate backwards, like so:

for( var j = localStorage.length-1; j>=i; j--) {

This will ensure that the dynamic length won't affect you.

btw, you can put an array in localStorage if you run it through JSON.stringify (and JSON.parse to get it back), or by joining it with a delimiter you know won't be in the elements (| is usually a good one) and splitting it later. Arrays are a LOT easier to work with.

Upvotes: 3

Related Questions