Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-11-2002, 11:15 AM   PM User | #1
WA
Administrator


 
Join Date: Mar 2002
Posts: 2,596
Thanks: 2
Thanked 19 Times in 18 Posts
WA will become famous soon enough
Function to retrieve client side cookie values

I must have used this function a hundred times now to retrieve a session only cookie, so I thought I'd post it here. It's very useful in painlessly retrieving the value of a cookie set using something like:


document.cookie="myname=George"

Here's the function, which was written by Shelley Powers and have long been released to the public freely:

Code:
function get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    // if cookie exists
    if (offset != -1) { 
      offset += search.length
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}
Usage:

1) Set a session only cookie using the syntax:

document.cookie="myname=George"

where "George" is the value of a cookie called "myname"

2) Then retreive "George, call the above function like so:

var result=get_cookie("myname")

Should the corresponding value not exist, the function returns an empty string.
__________________
- George
- JavaScript Kit- JavaScript tutorials and 400+ scripts!
- JavaScript Reference- JavaScript reference you can relate to.
WA is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:05 AM.


Advertisement
Log in to turn off these ads.