Reputation: 23
I have a simple html form with around 20-30 fields which has two buttons one is "Save" and the other is "Load".
I am trying to work out a way in which I can run two functions one to save all fields on the form as a cookie and the other to load all the fields back to the form from the cookie.
I have managed to save individual parameters as a cookie from the form, but I have not been able to do this in an array. Also I cannot seem to pull up each saved parameter I have tried getcookie
but this doesn't work and I have to use document.cookie
as setcookie
isn't working either.
document.cookie="firstname="+document.getElementById('firstname').value+"; expires=Thu, 18 Dec 2019 12:00:00 UTC";
document.cookie="secondname="+document.getElementById('secondname').value+"; expires=Thu, 18 Dec 2019 12:00:00 UTC";
Upvotes: 0
Views: 1668
Reputation: 1398
What method are you using to set your cookie values as an array? The document.cookie method should only take strings. Here is a simple way to set and get a cookie array:
function setCookieArray(cname, arrayValues, exdays) {
var expires = "";
if (exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
expires = ";expires="+ d.toUTCString();
}
var json_str = JSON.stringify(arrayValues);
document.cookie = cname + "=" + json_str + expires + ";path=/";
}
function getCookieArray(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return JSON.parse(c.substring(name.length, c.length));
}
}
return "";
}
You can set the cookie like this:
setCookieArray("myTest1", ["a","b","c","d"], 3); //expires in 3 days
And get the cookie array like this:
getCookieArray("myTest1");
Upvotes: 1