Skip to content

Instantly share code, notes, and snippets.

@townivan
Created July 16, 2014 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save townivan/d24c9477723e1cb308fa to your computer and use it in GitHub Desktop.
Save townivan/d24c9477723e1cb308fa to your computer and use it in GitHub Desktop.
Use localstorage instead of cookies
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form id="form1">
<p>This is an example of using localstorage instead of cookies.</p>
<p>As you leave each field it saves that field to localStorage. Try typing something into a box, tabbing/clicking our of that box and then refreshing the page to see that it remembers. By default the reset button clears the fields in the form, but I've added extra code to also clear the localStorage on reset.</p>
Field #1: <input type="text" id="field1"><br><br>
Field #2: <input type="text" id="field2"><br><br>
Field #3: <input type="text" id="field3"><br><br>
<input id="resetBtn" type="reset" value="Reset">
<input type="submit" value="Submit">
</form>
<br>
<a href="http://caniuse.com/#search=localstorage">http://caniuse.com/#search=localstorage</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
if(typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
// BEGIN LOAD FROM local storage
$('#field1').val(localStorage.getItem("field1"));
$('#field2').val(localStorage.getItem("field2"));
$('#field3').val(localStorage.getItem("field3"));
// END LOAD FROM local storage
// BEGIN SAVE to local storage
$( "#field1" ).change(function() { localStorage.setItem("field1", $('#field1').val()); });
$( "#field2" ).change(function() { localStorage.setItem("field2", $('#field2').val()); });
$( "#field3" ).change(function() { localStorage.setItem("field3", $('#field3').val()); });
// END SAVE to local storage
} else {
// Sorry! No Web Storage support..
alert('local storage NOT SUPPORTED');
}
$(function() {
$('#resetBtn').click(function() {
if(confirm("Are you sure that you want to clear all form data?")){
//alert('now reset the form');
localStorage.removeItem("field1");
localStorage.removeItem("field2");
localStorage.removeItem("field3");
}
else{
return false;
}
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment