HTML5 localStorage

Last Updated on March 21, 2018

As an exercise, I wanted to use vanilla javascript and localStorage() to take two items from the input fields, store them in localStorage, then get those stored items and place them as values back into the inputs. Finally clearing all localStorage contents and the input fields.

The HTML looks like this:






The JS looks like this:


var stbt = document.getElementById("storage");
stbt.addEventListener("click", storeIt, false);

var rtbt = document.getElementById("retrieve");
rtbt.addEventListener("click", retrieve, false);

var clbt = document.getElementById("clear");
clbt.addEventListener("click", clear, true);

var elv = document.getElementsByClassName('q');

function storeIt() {
	for (var i = 0; i < elv.length; i++) {
		var theVal = elv[i].value;
		if(theVal == '') { 
			alert("Enter content, because localStorage will save empty stings."); 
			return false; 
		}
		var storeName = elv[i].className + [i];
		localStorage.setItem(storeName, theVal);
	}
	alert("You've stored items. Refresh and click 'Get Items' to re-populate the fields.");
}

function retrieve() {
	if (window.localStorage.length == 0) { alert("Nothing stored!"); }
	for (var i = 0; i < localStorage.length; i++){
    	var obj = localStorage.getItem(localStorage.key(i));
    	document.getElementById('q'+[i]).value = localStorage.getItem('q'+[i]);
	}
}
function clear() {
  localStorage.clear();
  var vlu = document.getElementsByClassName('q');
  for (var i = 0; i < vlu.length; i++){
    vlu[i].value = '';
  }
}

And finally a Codepen.io if you'd like to play with it:

See the Pen Load JsonP File From Cross Domain Server And Store In localStorage() by Peter (@peterdillon) on CodePen.