Skip to content Skip to sidebar Skip to footer

Trying To Remove Item From Localstorage Using The Key Name

I am trying to remove item from localstorage or rather clear it on button click. I have written the code but on clicking on the button, it does not clear the localstorage data. thi

Solution 1:

You're successfully removing the item — and then when you refresh, you're setting it again as you leave the page, because you still have:

window.onbeforeunload = function() {
    localStorage.setItem("first_name", $('#inputName').val());
};

You'll have to decide when you want to set the item. The above will always do it, even if you've cleared it previously.

Perhaps you'd be better off only setting the item when the input changes, and not in onbeforeunload. That is, getting rid of the above, and instead:

$("#inputName").on("input", function() {
    localStorage.setItem("first_name", $(this).val());
});

That way, if you clear the item (remove it from local storage), it won't get added back unless you edit the field again.

Solution 2:

The code for setting/clearing the local storage looks good. However, the input field is not real-time synched with your local storage so, if you want your input to be always up to date with your local storage value, you should update it inside the clearStorage function in this way. Also you don't need to refresh the page if you use this approach:

window.onload = function() {
  var name = fetchLocalStorage();

  if (name !== null) {
    $('#inputName').val(name);
    alert(name);
  }
};

functionfetchLocalStorage() {
  returnlocalStorage.getItem("first_name");
}

functionclearStorage() {
  // clear local storagelocalStorage.removeItem('first_name');
  alert('localstorage cleared!');

  // update input valuevar name = fetchLocalStorage();
  $('#inputName').val(name);
}

functionsaveStorage() {
  localStorage.setItem("first_name", $('#inputName').val());
}

And the HTML should be updated to:

<input type="text"id="inputName" placeholder="Name" required>
<button type="button" onclick="saveStorage()">save</button>
<button type="button" onclick="clearStorage()">clear</button>

Solution 3:

uhm, try adding type="button" to your button... this prevents the form submit + page reload + onbeforeunload -> where your storage item gets set every time... https://developer.mozilla.org/en/docs/Web/HTML/Element/button#attr-type

Post a Comment for "Trying To Remove Item From Localstorage Using The Key Name"