Adding Cookies in JavaScript

Cookies can be added by using document object of JavaScript. Here while adding we have to add life of the cookies by adding expire date. Here is the simple code to add the cookies.

document.cookie="string of data & value separated by ; "

We will start with a simple one line cookie without any expire date. Cookies are stored as name value pairs separated by semi columns ; . We will start with a simple example of storing a name in cookies.

document.cookie="name" + "=" + name; // name is a variable

Adding expire date or life of the cookies

We will learn how to add expire date and time to the cookies. This is the life of the cookies in user computer after which cookies will be deleted. However if the user wishes they can remove cookies any point of time. If we are not adding any expire date to the cookies then the life of the cookies will last till the browser session only, once the browser is closed the cookies will be deleted. Here is the syntax to add expire date to our data.

document.cookie="name" + "=" + vlaue + ";expires="+dt.toUTCString();

Here value is the data which we will store against name. dt is the date object and we are converting to Universal Standard by using toUTCString function.

This sample code will add cookies for one day. To do this we will add the user to enter its name. Then on submit we will execute a function. Inside this function we will create a date object., collect the date part by using getDate() and then set the new date by adding one day and using setDate function. Then we will store the cookie. Here is the code.

<html>
<head>
<script type="text/javascript">
function add_cookies(){
var name=document.f1.t1.value;
dt= new Date();
var mts=dt.getDate(dt) + 1;
dt.setDate(mts);
document.write(dt);
document.cookie="name" + "=" + name + ";expires="+dt.toUTCString();
//var str="name" + "=" + name + ";expires="+dt.toUTCString();
//document.write("<br><br>" + str);
}
</script>
</head>
<body>
<form name=f1 method=post action=''><input type=text name=t1><input type=button onclick='add_cookies()'; value='Add Cookies'></form>

<br><br>
<a href=add-cookies.htm>Add Cookies</a> | <a href=read-cookies.htm>Read Cookies</a> | <a href=delete-cookies.htm>Delete Cookies</a>
</body>
</html>

You can check this code in this DEMO of cookies


plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer