I'm trying to create an application, that takes in multiple values with cookies, however it seems my setCookie function is not taking in multiple, but instead replacing each value when I enter a new one, so the showCookie functions only displays last value entered.
setCookie:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
storeValues function:
function storeValues()
{
var note= document.getElementById("note").value;
setCookie("note",note,365);
alert("Cookies stored!")
}
show functions:
function show()
{
var note= document.getElementById("note").value;
alert("Note:" + note );
}
function showall()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
alert("Key is : " + name + " and Value is : " + value);
}
}
You need to change from assignment operator (=
) to concatenation and assignment compound operator (+=
).
It would also be a good idea to overwrite the cookie key if it exists. So I'd recommend turning the cookie values into an object, modifying them and then serialising back to a cookie string.