PDA

View Full Version : Saving a list of items in a cookie...



hotmonkeyac
09-28-2007, 08:56 PM
I have a script that will allow users to add links to a <div> box as a list. It's a simple script but I would like to know if its possible to store the results of the pages they add in a cookie (for future visits). Here is the code:


<script type="text/javascript">
<!--

function addEvent()
{
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById("theValue").value -1)+ 2;
numi.value = num;
var divIdName = "my"+num+"Div";
var newdiv = document.createElement('div');
newdiv.setAttribute("id",divIdName);
newdiv.innerHTML = "Added! <a href=\"javascript:;\" onclick=\"removeEvent(\'"+divIdName+"\')\">Remove</a>";
ni.appendChild(newdiv);
}

function removeEvent(divNum)
{
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}

//-->
</script>

Then, the following code is placed in the body:


<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:;" onclick="addEvent();">Add</a></p>
<div id="myDiv"> </div>

When the user clicks "Add", it adds the page to their list. Can someone please help me store this in a cookie? Thank you.

Edit: Even if someone can point me in the direction of a simple script that stores a list of items as a cookie, I should be able to figure it out.

jscheuer1
09-29-2007, 04:48 AM
If you need help setting and retrieving cookie values, see:

http://www.quirksmode.org/js/cookies.html

for a good explanation of and code for cookies, generally.

Once you have that down, storing multiple values in a cookie is pretty easy. First thing to remember is that you can only store strings in cookies. If you want to use the same cookie name, adding and/or subtracting data to/from it as you go along, you must try to read it to see if it has any existing value and what that might be and set it each time.

Adding multiple values to a cookie is best done with a delimiter. This should be one not used by cookies and a character not likely to occur in your data. $ is often a good choice. $$ can even be better.

Now all you need to do is make an array of your values and then join() it into a string with your chosen delimiter, and store it in the cookie. When you retrieve it, you can then split() it back into array on your delimiter to test it's items against pre-established or on-the-fly values.