/    Sign up×
Community /Pin to ProfileBookmark

Save Form Value into a Cookie

Hi all,

I am having a nightmare of a time trying to save a form value into a cookie. I am using the following:-

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=/”;
}

and then

createCookie(‘TestCookie’,’TestVal’,7)
createCookie(‘VisitorName’, document.forms[0].name.value, 365)

TestCookie is saved OK but VisitorName won’t. What is wrong with passing document.forms[0].name.value as the value for VisitorName ?

Or is there another way to do this?

Cormac

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@sdi126Jan 17.2007 — Well there could be a few things wrong with this. Some things to look for are:

1) document.forms[0] is referring to the first form on the page. So if you have more than one form on the page you might be trying to access a value on a different form.

2.) document.forms[0].name.value "name" is referring to the actual name give to the form item....im assuming an input box.

Can we see the form code?
Copy linkTweet thisAlerts:
@championcauthorJan 17.2007 — Thanks for taking the time to look at this. I am testing this with Firefox 2.0.0.1. I have loaded my server with a test form

www.syngestreetppu.com/index1.html

Strangely I was able to get it working when I used a different setcookie function which inserted quotes around the value. However, this then saved the cookie with the name "SyngerName (a quote mark before the Name) and I couldn't find any way of doing it.

function setCookie(NameOfCookie, value, expdays) {

var ExpDate = new Date ();

ExpDate.setTime(ExpDate.getTime() + (expdays * 24 * 3600 * 1000));

var newString = NameOfCookie + "=" + escape(value) +

((expdays == null) ? "" : "; expires=" + ExpDate.toGMTString());

document.cookie = '"' + (newString) + '"'

}



Cormac
Copy linkTweet thisAlerts:
@championcauthorJan 17.2007 — Can anyone help me please as to how I can pass the contents of this form into a cookie ?

I'm desperate.


C
×

Success!

Help @championc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...