Set and get multiple cookies in JavaScript04:33

  • 0
Published on November 22, 2017

Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

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.

When we click “Set Cookie” button we want to store the following 3 key-value pairs in 3 cookies.
name=Venkat;
[email protected];
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 protected]; 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(“No cookies found”);
}
}

Enjoyed this video?
"No Thanks. Please Close This Box!"