fre2ak
fre2ak

Reputation: 329

jQuery html5 localStorage removeItem error

Here in this code:

$('#doneItem').click(function(){
        $(this).each(function(index){
            var item = 'personal' + index;
            alert(item);
            localStorage.removeItem('personal' + index);
            window.location.reload(true);
        });
});

#doneItem is a button, and i want to remove the 'personal0' for ex. from localStorage and... Uncaght TypeError: Cannot call method 'removeItem' of undefined. Any ideas??

Upvotes: 0

Views: 7040

Answers (1)

Niklas
Niklas

Reputation: 13145

Could you check if the item is in the localStorage before trying to remove it?

if (item in localStorage) localStorage.removeItem(item);  

I assume you've checked that the browser uses localStorage?

EDIT
You can try to use a dynamic id. This will match all a elements that start with doneItem and then get the number at the end to the index variable.

    $("a[id^=doneItem]").click(function(){
            var index = $(this).attr("id").replace("doneItem", "");                
            var item = 'personal' + index;
            localStorage.removeItem(item);
            window.location.reload(true);
    });  

You would also need to change this line and insert an i there:

document.write("<a data-role=\"button\" id=\"doneItem" + i + "\" data-transition=\"none\" href=\"#showPersonal\" data-icon=\"check\" data-iconpos=\"left\">Done</a>");  

This will only work if you comment out the Modernizr code too. You're replacing the localstorage variable here, and I don't know why you do that.

    /*   
    if (Modernizr.localstorage) {
          var localStorage = window.storage;
    } else {
          alert('Your browser does not support local storage!');
    }
    */  

These problem might only be with jsfiddle so I had to remove some more code, but here's a somewhat working example: http://jsfiddle.net/zr4tg/53/

It might not look like you want but it should be working. Let me know =)

Upvotes: 1

Related Questions