I\'m trying to set multiple cookies in document.cookie
, but unfortunately only one is getting added.
I know there are multiple examples present on the \'Net
Adding a cookie is performed via document.cookie = "name=value"
to add multiple keys, you should perform multiple assigments
function setCookie(start_time, end_session_time, total_time, flag, count) {
document.cookie = "start_time=" + start_time;
if (end_session_time) {
document.cookie = "end_session_time=" + end_session_time;
}
if (total_time) {
document.cookie = "total_time=" + total_time;
}
if (flag) {
document.cookie = "flag=" + flag;
}
if (count) {
document.cookie = "count=" + count;
}
console.log("document.cookie = " + document.cookie);
}
Cookies are key value pairs (with some optional additional info added on, like the expiry date). To set more than one, you just set document.cookie
more than once. The ;
separator is used to specify the additional info, not to add more different cookies.
There you go a sample example to add, list and delete multiple cookies
<!DOCTYPE html>
<html>
<head>
<script>
var n=1;
function addCookie(){
document.cookie=n+"="+n;n++;
}
function ListCookies(){
var result = document.cookie;
document.getElementById("p").innerHTML=result;
}
function removeCookies(){
//document.cookie="";
var result = document.cookie;
var cookieArray = result.split(";");
for(var i=0;i<cookieArray.length;i++){
var keyValArr = cookieArray[i].split("=");
document.cookie=keyValArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</head>
<body>
<button onclick='addCookie()'>ADD COOKIE</button><br>
<button onclick='ListCookies()'>LIST COOKIES</button>
<button onclick='removeCookies()'>REMOVE COOKIES</button>
<h1>RESULT:</h1>
<p id="p"></p>
</body>
</html>