Setting multiple cookies in Javascript

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 for setting up these kind of cookies,and I followed one of them. But still I’m unable to set that out.
I followed this link to set my cookie.

My Code:

   function setCookie(start_time,end_session_time,total_time,flag,count){
     var cookie_string = "start_time="+start_time;;

    if(end_session_time) {
        cookie_string +="; end_session_time="+end_session_time;
    }

    if(total_time){
        cookie_string +="; total_time="+total_time;
    }
    if(flag){
        cookie_string +="; flag="+flag;
    }
    if(count){
        cookie_string +="; count="+count;
    }

    document.cookie =cookie_string ;
    console.log(cookie_string);

    console.log("document.cookie ="+ document.cookie);
}

The Output:

cookie_string :: start_time=1369926508266; flag=1; count=1
document.cookie =start_time=1369926508266; 

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>


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   how to load Javascript in Wordpress Plugin

Similar Posts