Skip to content

Instantly share code, notes, and snippets.

@benjaminrau
Last active January 25, 2016 16:25
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 benjaminrau/9eb0e4ba27e4a483dfeb to your computer and use it in GitHub Desktop.
Save benjaminrau/9eb0e4ba27e4a483dfeb to your computer and use it in GitHub Desktop.
HTML5 LocalStorage used to fill form
<script>
$(document).ready(function() {
function initFormStorage(registrationFormId) {
console.log('Initializing storage for form#' + registrationFormId);
/*
* when a form field changes store it's value in local storage
*/
$("#" + registrationFormId + " input[type=text], #" + registrationFormId + " select, #" + registrationFormId + " textarea").change(function() {
$this = $(this);
console.log('Update value for ' + $this.attr("name") + 'to ' + $this.val());
localStorage.setItem($this.attr("name"), $this.val());
});
$("#" + registrationFormId + " input[type=checkbox]").change(function() {
$this = $(this);
localStorage.setItem($this.attr("name"), $this.attr("checked"));
});
$("#" + registrationFormId).submit(function() {
localStorage.clear();
});
$.each(localStorage, function(name, value) {
if ($("[name='" + name + "']").is("select")) {
$("[name='" + name + "']").find("option[value=" + value + "]").attr("selected", true);
} else {
switch ($("[name='" + name + "']").attr("type")) {
case "checkbox":
if (value == "checked") {
$("[name='" + name + "']").attr("checked", "checked");
}
break;
default:
$("[name='" + name + "']").val(value);
}
}
});
}
if (localStorage) {
$("form").each(function () {
initFormStorage($(this).attr('id'));
});
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment