View Full Version : Writing and Reading Cookies with Javascript

11-20-2010, 08:13 PM
I've looked on several websites and several threads here regarding writing and reading cookies with javascript, and I just can't seem to get it to work. All I want is a simple text box with 2 buttons: Save and Recall. Text entered into box is saved to a cookie when "Save" is pressed, and at a later date when "Recall" is pressed the saved text will show up in the box.

Can you help please?

Philip M
11-20-2010, 08:51 PM
Cookies have been covered very many times in this forum. Did you try using the Search feature?

<input type = "text" id = "txtInput">
<input type = "button" value = "Save" onclick = "createCookie('mycookie', document.getElementById('txtInput').value, 10)">
<input type = "button" value = "Recall" onclick = "readCookie('mycookie')">

<script type = "text/javascript">

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = "; expires = "+ date.toGMTString();
else{var expires = ""}
document.cookie = name + "=" + value + expires + "; path=/"; // available throughout the directory

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var cb = ca[i];
while (cb.charAt(0)==' ') {cb = cb.substring(1,cb.length)}
if (cb.indexOf(nameEQ) == 0) {
retval = cb.substring(nameEQ.length,cb.length);
document.getElementById("txtInput").value = retval;
return retval;
return null; // no display if cookie not found

function eraseCookie(name) {
createCookie(name,"",-1); // set cookie to expire on previous day

//eraseCookie("mycookie", "", -1); // if required for testing


10 means 10 days, the number of days persistence for the cookie before it expires. Adjust the number to suit your requirements.

Once a powerful king went to see an old hermit who lived in a bird's nest in the top of a tree, and asked "What is the most important Buddhist teaching?"
The hermit answered, "Do no evil, do only good. Purify your heart." The king had expected to hear a very long explanation. He protested, "But even a five-year old child can understand that!" "Yes," replied the wise sage, "but even an 80-year-old man cannot do it."

Old Pedant
11-20-2010, 08:58 PM
Look in this thread:

Shows saving and recalling the value of a button, so it's really the same thing. Just use the value of your text field instead.

11-20-2010, 09:59 PM
Thank you both! I'll try with your help to accomplish what I want. If not, I guess I'll be back to ask for further assistance :)

And yes, as I mentioned in the OP I used the search feature for this problem, but I didn't understand the several threads I looked at.