Introduction
In this article, we will tell how to save and get cookies using JavaScript.
Procedure to save a value in cookies using JavaScript
In the following function we pass three parameters:
- c_name: the name of the cookie (that you want to create)
- value: the value you want to save in the cookie
- expiredays: expiry days of your cookie
- function setCookie(c_name, value, expiredays) {
- var exdate = new Date();
- exdate.setDate(exdate.getDate() + expiredays);
- document.cookie = c_name + "=" + value + ";path=/" + ((expiredays ==null) ? "" : ";expires=" + exdate.toGMTString());
- }
Procedure to get the value from a cookie
In the following function we pass one parameter:
- Name- Name of the cookie that you want to get the value of.
- function getCookie(name) {
- var dc = document.cookie;
- var prefix = name +"=";
- var begin = dc.indexOf("; " + prefix);
- if (begin == -1) {
- begin = dc.indexOf(prefix);
- if (begin != 0)return null;
- } else {
- begin += 2;
- }
- var end = document.cookie.indexOf(";", begin);
- if (end == -1) {
- end = dc.length;
- }
- return unescape(dc.substring(begin + prefix.length, end));
- }
Example
This is the simple live example of how to use a cookie in your application:
- <scriptlanguage="javascript"type="text/javascript">
- function setCookie(c_name, value, expiredays) {
- var exdate = new Date();
- exdate.setDate(exdate.getDate() + expiredays);
- document.cookie = c_name + "=" + value + ";path=/" + ((expiredays ==null) ? "" : ";expires=" + exdate.toGMTString());
- }
- function getCookie(name) {
- var dc = document.cookie;
- var prefix = name +"=";
- var begin = dc.indexOf("; " + prefix);
- if (begin == -1) {
- begin = dc.indexOf(prefix);
- if (begin != 0)return null;
- } else {
- begin += 2;
- }
- var end = document.cookie.indexOf(";", begin);
- if (end == -1) {
- end = dc.length;
- }
- return unescape(dc.substring(begin + prefix.length, end));
- }
- function savename() {
- setCookie("SetName", document.getElementById("textName").value, 1);
- }
- function getName() {
- var strVal = getCookie("SetName");
- var name = document.getElementById("textName").value;
- if (strVal == name) {
- alert("hi i am " + name);
- }
- }
- </script>
- <formid="form1"runat="server">
- <inputtype="text"id="textName"onblur="savename();"/>
- <inputtype="button"onclick="getName();"value="Click"/>
- </form>