Click here to Skip to main content
15,896,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

SetItem() and getItem() work with the following code, but not removeItem(). Do I need to format the object before removing it? Code below. Cheers.

<!DOCTYPE HTML>
<html>
<body>

<script>

function storeusername()
{
	var person = {};
	person.age = 25;
	person.firstname = 'Joe';
	person.lastname = 'Smith';
	localStorage.setItem('persondetails', JSON.stringify(person));
}

function getusername()
{
	var person = JSON.parse(localStorage.getItem('persondetails'));
	document.getElementById('username').innerHTML = person.age + ' ' + person.firstname + ' ' + person.lastname;
}

function clearusername()
{
	localstorage.removeItem('personaldetails');
}

</script>
<br/>
Name: <p id="username"></p>
<input type=button value="Store" onclick="storeusername()" />
<input type=button value="Retrieve" onclick="getusername()" />
<input type=button value="Clear" onclick="clearusername()" />
</body>
</html>
Posted

1 solution

removeItem is correct, but you have to specify the right key. To add stuff you use persondetails and to remove you use personaldetails, so that's not going to work.

JavaScript
// localStorage is with capital S (very important, localstorage is undefined).
// The key is persondetails, and not personaldetails.
localStorage.removeItem('persondetails');
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900