Skip to content

Instantly share code, notes, and snippets.

@moabi
Created December 29, 2016 08:48
Show Gist options
  • Save moabi/cddf4a96635e4d7853f754d0d085994a to your computer and use it in GitHub Desktop.
Save moabi/cddf4a96635e4d7853f754d0d085994a to your computer and use it in GitHub Desktop.
store inputs/selects to sessionsStorage, if page is reloaded, set form inputs values
/**
* 1/ onLoad, retrieve session storage data (ALL OF IT !!! - so carefull)
* 2/ the key === input/select ID
* 3/ set the value
*/
window.onload = function () {
if (sessionStorage) {
for (i = 0; i < sessionStorage.length; i++) {
var key = sessionStorage.key(i);
var value = sessionStorage[key];
setField(key, value);
}
}
};
/**
* saveFormData
* only inputs & selects
*/
function saveFormData() {
// Check for LocalStorage support.
if (sessionStorage) {
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; ++i) {
elId = inputs[i].id;
elVal = inputs[i].value;
if (typeof elId !== "undefined") {
storeField(elId, elVal);
}
}
var selects = document.getElementsByTagName("select");
for (i = 0; i < selects.length; ++i) {
elId = selects[i].id;
elVal = selects[i].value;
if (typeof elId !== "undefined") {
storeField(elId, elVal);
}
}
}
}
/**
* sessionStorage store action
* @param idName
* @param val
*/
function storeField(idName, val) {
sessionStorage.setItem(idName, val);
}
/**
* sessionsStorage set value field according to its ID
* @param idName
* @param val
*/
function setField(idName, val) {
el = document.getElementById(idName);
if (el !== null) {
el.value = val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment