UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Cookies in javascript

Demo and code for how to Add and Read values from cookies using javascript

by Athil


Posted on 01 Jan 0001 Category: Javascript Views: 2191


Cookies are the values that are stored in the Web browser memory,  here I am going to show how to add, read values from cookies.

DEMO

Adding values to cookies

 document.cookie = "cookiename=" + value;

Where 'cookiename' is the name of cookie and value the variable that having value to add in cookie.

Reading values from cookies

   var CookieName = "cookiename=";
   var DecodedCookie = decodeURIComponent(document.cookie);
   if (DecodedCookie != null) {
      var CookieArray = DecodedCookie.split(';');
      for (var i = 0; i < CookieArray.length; i++) {
          var c = CookieArray[i];
          while (c.charAt(0) == ' ') {
              c = c.substring(1);
          }
          if (c.indexOf(CookieName) == 0) {
              alert(c.substring(CookieName.length, c.length));
           }
        }
    }
    else {
        alert('No cookie exist!');
    }

Where 'cookiename' is the name of cookies and taking all cookies and splitting all cookies and matching the name of cookie you are given and taking the value.



Leave a Comment:


Click here to register

Popular articles