Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Storing & retrieving form fields in a JSON cookie
/* Storing & retrieving form fields in a JSON cookie
* copyright Will Bradley, 2012, released under a CC-BY license
*
* Change all instances of "myform" as necessary.
* Cookie will be stored under the current URL, but
* it won't include any hidden fields, etc.
*/
function setCookie(c_name,value,expireminutes)
{
var exdate=new Date();
exdate.setMinutes(exdate.getMinutes()+expireminutes);
document.cookie=c_name+ "=" +escape(value)+
((expireminutes==null) ? "" : ";expires="+exdate.toUTCString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function onSubmit()
{
var form=document.myform;
var json = [];
// Loop through all the form elements
for (var i=0;i<form.length;i++) {
// Make sure they're valid to be stored (i.e. checked, not a button)
if (form.elements[i].name && (form.elements[i].checked
|| /select|textarea/i.test(form.elements[i].nodeName)
|| /text|password/i.test(form.elements[i].type))) {
// Store them in an object association
var entry = {};
entry[form.elements[i].name] = form.elements[i].value;
json.push(entry);
//alert(form.elements[i].id+": "+form.elements[i].value);
}
}
setCookie("myform",JSON.stringify(json),1);
//alert(JSON.stringify(json));
}
function onLoad() {
// load values from cookie
var cookie = getCookie("myform");
if(cookie.length > 10){
var retval = JSON.parse(cookie);
//alert(retval.length);
for(var i=0;i<retval.length;i++) {
var obj = retval[i];
for(var key in obj){
//alert(key+": "+obj[key]);
document.myform.elements[key].value = obj[key];
}
}
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script language="JavaScript" src="form-field-json-cookies.js"></script>
</head>
<body onload="onLoad()">
<form id="myform" name="myform" onsubmit="return onSubmit()">
<!-- your form fields here (hidden fields will not be cookified) -->
<input type="text" name="a" />
<input type="text" name="b" />
<input type="submit" value="Go" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.