How to save, retrieve and remove data with JavaScript and HTML5



Thanks to localStorage. Saving, retrieving and removing temporary data is very easy. To save data, we call this function: localStorage.setItem(); To retrieve data, we call localStorage.getItem(); and to remove it we call localStorage.removeItem();.

Below is simple source code to show you how this three functions work:

<!DOCTYPE html>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<title>Experiments</title>
		<style>
			.myBox{
				border: 1px solid black;
				padding: 10px;
				margin-bottom: 10px;
			}
		</style>
	</head>
	<body>
		<script>
			//localStorage.removeItem(key);
		</script>
		<div class="myBox">
			<h1>Saving Data</h1>
			<input id="myInput" placeholder="Type anything...">
			<button onclick="saveData()">Save</button>
		</div>
		<div class="myBox">
			<h1>Saved Data</h1>
			<p id="savedData"></p>
		</div>
		<div class="myBox">
			<h1>Delete Data</h1>
			<button onclick="deleteData()">Delete</button>
		</div>
		<script>
			if(localStorage.getItem("myData") ===  null) document.getElementById("savedData").innerHTML = "No data is saved.";
			else document.getElementById("savedData").innerHTML = "Saved data: " + localStorage.getItem("myData");
			function saveData(){
				var newData = document.getElementById("myInput").value;
				if(newData != "") localStorage.setItem("myData", newData);
				location.reload();
			}
			function deleteData(){
				if(localStorage.getItem("myData") !== null) localStorage.removeItem("myData");
				location.reload();
			}
		</script>
	</body>
</html>

You can see live result of these codes here:

loading...