Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Set and get multiple cookies in JavaScript

Suggested Videos
Part 67 - JavaScript Cookies
Part 68 - JavaScript cookie attributes
Part 69 - Store multiple key value pairs in a cookie



In this video, we will discuss how to set and get multiple cookies in JavaScript. This is continuation to Part 69. Please watch Part 69 before proceeding.



javascript cookie multiple keys

When we click "Set Cookie" button we want to store the following 3 key-value pairs in 3 cookies.
name=Venkat;
email=Kudevnkat@gmail.com;
gender=Male;

When we click "Get Cookie" button we want to retrieve all the 3 key-value pairs from the 3 cookies

Modify the code in setCookie() function as shown below. 
function setCookie()
{
    document.cookie = "name=" + document.getElementById("txtName").value;
    document.cookie = "email=" + document.getElementById("txtEmail").value;
    document.cookie = "gender=" + document.getElementById("txtGender").value;
}

The above code creates 3 cookies and stores the 3 key-value pairs. At this point document.cookie property contains the following string
"name=Venkat; email=Kudvenkat@gmail.com; gender=Male"

Now, modify the code in getCookie() function as shown below. 
function getCookie()
{
    if (document.cookie.length != 0)
    {
        var cookiesArray = document.cookie.split("; ");

        for (var i = 0; i < cookiesArray.length; i++)
        {
            var nameValueArray = cookiesArray[i].split("=");

            if (nameValueArray[0] == "name")
            {
                document.getElementById("txtName").value = nameValueArray[1];
            }
            else if (nameValueArray[0] == "email")
            {
                document.getElementById("txtEmail").value = nameValueArray[1];
            }
            else if (nameValueArray[0] == "gender")
            {
                document.getElementById("txtGender").value = nameValueArray[1];
            }
        }
    }
    else
    {
        alert("Cookies not found");
    }
}

JavaScript tutorial

3 comments:

  1. Hello kudvenket please up lode some vedio related to real time project how to create and develop and I need PayPal intregation own website help me this topic thanks

    ReplyDelete
  2. Sir please upload videos for HTML 5 and CSS 3

    ReplyDelete
    Replies
    1. Sir ,Thanks for this effort i realy think you are a great explainer of any topic plzz upload a video how we can upload our data on real time server like any company server
      Thanks

      Delete

It would be great if you can help share these free resources