View Full Version : creation and usage of cookies using javascript

06-17-2008, 06:14 AM

I have developed an application where i can create cookie and use that cookie. But the problem is every time when i create the cookie that cookie is going to replace all the previous cookies. Means I am getting only the last created cookie only. How can I create and use multiple cookies.

Thank you in advance...

Philip M
06-17-2008, 09:09 AM
Just give the cookies different names.

document.cookie =
'mycookie1= testcookie; expires=Tues, 17 Jun 2008 19:47:11 UTC; path=/'

document.cookie =
'mycookie2=another test; expires=Tues, 17 Jun 2008 20:47:11 UTC; path=/'

The first cookie is not overwritten, as it would when if document.cookie was be a real string. Instead the second one is added to document.cookie, so if we read it out we get:-

mycookie1=testcookie; mycookie2=another test

If you reset a cookie:-

document.cookie =
'mycookie2=yet another test; expires= Tues, 17 Jun 2008 21:45:11 UTC; path=/'

the old cookie is overwritten and document.cookie now reads

mycookie1=testcookie; mycookie2=yet another test


06-17-2008, 09:12 AM
You name the cookies differently. I prefer to use one or just a few cookies for sites, broken out by functionality, or areas of the site. So you could use a string with unique separators between the different settings/states that you wish to save, and so which may be converted into an array after loading the cookie. Save the string as the cookie. But if you want a bunch of separate cookies cluttering that web site, just use different names for the cookies.