Last active
January 25, 2016 16:25
-
-
Save benjaminrau/9eb0e4ba27e4a483dfeb to your computer and use it in GitHub Desktop.
HTML5 LocalStorage used to fill form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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