JSFiddle - React, Tailwind, and code Playground
HTML
<div id="example">
<div>
<label for="fullName">Name:</label>
<input type="text" id="fullName" />
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" />
</div>
<div>
<input type="button" id="setStorage" value="Save to Storage" />
<input type="button" id="loadStorage" value="Load From Storage" />
</div>
<div>
<input type="button" id="clearFields" value="Clear Fields" />
<input type="button" id="clearStorage" value="Clear Storage" />
</div>
</div>
CSS
label {
float: left;
min-width: 5em;
}
label:after {
clear:both;
}
input[type="button"] {
width: 12.5em;
margin: 1em 1em 0 0;
}
JavaScript
// cache our selectors
var $name = $("#fullName");
var $loc = $("#location");
var store = {
// store our input values as members of an object that gets
// serialized, since local storage stores *strings*
saveToStorage: function () {
localStorage.setItem("example", JSON.stringify(this.getInputValues()));
},
// a bit naive, but we parse the JSON into an object
// and if we get something, we set our input values
loadFromStorage: function () {
var store = JSON.parse(localStorage.getItem("example"));
if (store) {
$name.val(store.fullName);
$loc.val(store.location);
}
},
clearFields: function () {
$name.val("");
$loc.val("");
},
clearStorage: function () {
localStorage.clear();
},
getInputValues: function () {
return {
fullName: $name.val(),
location: $loc.val()
};
}
};
// hook up event handlers
$("#setStorage").on("click", $.proxy(store.saveToStorage, store));
$("#loadStorage").on("click", $.proxy(store.loadFromStorage, store));
$("#clearFields").on("click", store.clearFields);
$("#clearStorage").on("click", store.clearStorage);