You are on page 1of 2

Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

CSS Lecture-22
Topic: Creating And Manipulating Cookie in Java Script.
In JavaScript, we can create, read, update and delete a cookie by
using document.cookie property.

Creating Cookie:
The following syntax is used to create a cookie:
document.cookie="name=value";

Reading a cookie:
We can use document.cookie whenever we want to access the cookie, With
Javascript, cookies can be read like this
var str=document.cookie;

Example1: Following program gets user name of first page(cookie1.html) , then it


stores user name in cookie and display username on next page(page.html).
Cookie1.html
<html>
<body>
<form action="page.html" onsubmit="return addcookie()">

Enter your Name:<input id="t1" type="text" name="c_value"><br>


<input type="submit" value="Visit">
</form>

<script>
function addcookie(){
var t1 = document.getElementById("t1");
if(t1.value.trim().length==0)
{
alert("Enter name ");
return false;
}
document.cookie="name="+t1.value;
return true;
}
</script>
</body>
</html>

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260

Page.html
<html>
<body onload="load()">
<p id ="p1"></p>
</body>

<script>
function load(){
document.getElementById("p1").innerHTML=document.cookie;
}
</script>
</html>

Example2: Following Program Creates multiple cookies on first button click and
display all cookies on second button click.

cookie2.html
<html>

<body>
Cookie Name:<input id="t1" type="text" name="c_name"><br>
Cookie Value: <input id="t2" type="text" name="c_value"><br>

<input type="button" value="Add Cookie" onclick="addcookie()">

<input type="button" value="Display Cookie" onclick="displaycookie()">


</body>

<script>
function addcookie(){
var t1 = document.getElementById("t1");
var t2=document.getElementById("t2");
document.cookie=t1.value+"="+t2.value;
t1.value="";
t2.value="";

}
function displaycookie(){
alert(document.cookie);
}
</script>
</html>

Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260

You might also like