JavaScript Cookie with multiple Name

In order to store multiple name-value pairs of cookies in javascript, the custom object must be serialized in a JSON string which is then parsed and stored in a cookie. A separate cookie can also be used for each name-value pair. Example:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
Username: <input type="text" id="name"><br>
Mail_ID: <input type="email" id="email"><br>
Id: <input type="text" id="course"><br>
<input type="button" value="Set" onclick="setCookie()">
<input type="button" value="Get" onclick="getCookie()">
<script>
function setCookie()
{
var cook = {};
cook.name = document.getElementById("name").value;
cook.email = document.getElementById("email").value;
cook.course = document.getElementById("course").value;
var jsonString = JSON.stringify(cook);
document.cookie = jsonString;
}
function getCookie()
{
if( document.cookie.length!=0)
{
var cook = JSON.parse(document.cookie);
alert("Username="+cook.name+" "+"Mail_ID="+cook.email+" "+"Id="+cook.course);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com