
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set and Get Cookies with JavaScript
Set Cookie
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:
document.cookie = "key1=value1;key2=value2;expires=date";
Here the “expires” attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
Example
Try the following. It sets a customer name in an input cookie.
<html> <head> <script> <!-- function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue= escape(document.myform.customer.value) + ";"; document.cookie="name=" + cookievalue; document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name="myform" action=""> Enter name: <input type="text" name="customer"/> <input type="button" value="Set Cookie" onclick="WriteCookie();"/> </form> </body> </html>
Get Cookie
Reading a cookie is just as simple as writing one because of the value of the document.cookie object is the cookie. So, you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where the name is the name of a cookie and value is its string value.
Example
You can try to run the following code to read a cookie −
<html> <head> <script> <!-- function ReadCookie() { var allcookies = document.cookie; document.write ("All Cookies : " + allcookies ); // Get all the cookies pairs in an array cookiearray = allcookies.split(';'); // Now take key value pair out of this array for(var i=0; i<cookiearray.length; i++) { name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1]; document.write ("Key is : " + name + " and Value is : " + value); } } //--> </script> </head> <body> <form name="myform" action=""> <p> click the following button and see the result:</p> <input type="button" value="Get Cookie" onclick="ReadCookie()"/> </form> </body> </html>