/    Sign up×
Community /Pin to ProfileBookmark

Setting Cookies

Hey all. I’m new here. I’ve just started trying to use javascript and cookies to build myself a shopping cart/checkout system. Just playing with cookies and forms at the moment without much luck. Would anyone be able to give me a few tips on this code? The bolded/underlined sections are the parts i’m having problems with.

Any hints/tips would be much appreciated! This is frustrating stuff!

[CODE]<html>
<head>
<title>Cookie Example</title>
<script language=”javascript”>
<!–
expiry = new Date();
expiry.setMonth(expiry.getMonth()+1);
function setCookie(c_name,c_value)
{

document.cookie = c_name + “=” + c_value + “;expires=” + expiry.toGMTString();
}

//–>
</script>

</head>
<body leftmargin=”50″>

<form>
Select products
<p />
Product 1: <input type=”checkbox” name=”prouduct1″ [U][B]onChange=”Store info until button is pressed”>[/B][/U]
<br />
Product 2: <input type=”checkbox” name=”prouduct2″ [U][B]onChange=”Store info until button is pressed”>[/B][/U]
<p />
<input type=”button” value=”set cookie!” onClick=”javascript:setCookie[U][B](Info from checkboxes.. I.e. product1, product2, product3)[/B]”>[/U]
</form>
</body>
</html>[/CODE]

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@bals28mjkOct 11.2007 — Hi Reckoner.

I advise you use cookies for your server side language instead.
Copy linkTweet thisAlerts:
@ReckonerauthorOct 11.2007 — Thanks for your input. However I need this to be done in Javascript.
Copy linkTweet thisAlerts:
@ReckonerauthorOct 11.2007 — Actually I think i'm getting somewhere... This script works fine. My only problem is it only saves the first text box value in the cookie. I want it to save all text box names and values that are in the whole form.

Any ideas? Cheers! ?

[CODE]<HTML>
<HEAD>
</HEAD>
<SCRIPT LANGUAGE = "JavaScript">
<!--
// This function gets things set up, creates the cookie,
// and then moves to the next page
//
function BakeIt() {
// Get the value of the "data" field in the form
var cookieData = document.cookieForm.data.name.value;

// See if the data was entered
if (cookieData != null) {

// Use this variable to set the name of the cookie
var cookieName = "Products";

// Use this variable to set the number of days after which the cookie will expire
var days = 100;

// Calculate the expiration date
var expires = new Date ();
expires.setTime(expires.getTime() + days * (24 * 60 * 60 * 1000));

// Set the cookie
SetCookie(cookieName, cookieData, expires);
}

// Move to the next Cookies page
// Note that this is optional; you can delete this line if you want
window.location = "http://www.teamfbi.co.nz";
}

function SetCookie(cookieName, cookieData, expireDate) {
document.cookie = cookieName + "=" + escape(cookieData) + "; expires=" + expireDate.toGMTString();
}
//-->
</SCRIPT>

<BODY>

<FORM NAME="cookieForm" onSubmit="return false;">
Select Product: <INPUT TYPE="text" name="data" value="1" size="2" >
<br>
Select Product: <INPUT TYPE="text" name="data1" value="1" size="2" >
<P>
<INPUT TYPE="button" NAME="Product1" VALUE="Set The Cookie" onClick="BakeIt()">
</FORM>


</BODY>
</HTML>[/CODE]
Copy linkTweet thisAlerts:
@bals28mjkOct 11.2007 — However I need this to be done in Javascript.[/QUOTE]
Oh.Actually I think i'm getting somewhere... This script works fine. My only problem is it only saves the first text box value in the cookie. I want it to save all text box names and values that are in the whole form.

Any ideas? Cheers! [/QUOTE]

You might like this idea:
[CODE]<html>
<head>
<title>Cookie Example</title>
<script language="javascript">
<!--
expiry = new Date();
expiry.setMonth(expiry.getMonth()+1);
function setCookies()
{
var el=document.forms[0].elements
var l=el.length
var cName=[]
var cValue=[]

for(var i=0;i<l;i++)
{
if(el[i].checked)
{
cValue[i]=el[i].value
cName[i]=("pro" + i).toString()//String to name you want order e.g pro0,pro1,pro2...
}
}
if(cName.length > 0)
{
for(i=0; i<cName.length; i++)
{
document.cookie= cName[i] + "=" + cValue[i] + ";expires=" + expiry.toGMTString();
}
}

alert(document.cookie)
}
//-->
</script>

</head>
<body leftmargin="50">

<form>
Select products
<p />
Product 1: <input type="checkbox" value="apple" name="product1" />
<br />
Product 2: <input type="checkbox" value="banana" name="product2" />
<p />
</form>
<input type="button" value="set cookie!" onClick="setCookies()" />
</body>
</html>[/CODE]
Copy linkTweet thisAlerts:
@ReckonerauthorOct 11.2007 — Hm that looks promising! Not perfect but I think I can manage modifying that to suit.

Cheers, I really appreciate that! ?
Copy linkTweet thisAlerts:
@bals28mjkOct 11.2007 — Your welcome. How is it not perfect? I totally disagree with you.
Copy linkTweet thisAlerts:
@ReckonerauthorOct 11.2007 — Hmm a few problems with that one.

  • 1. If I click the 2nd and 3rd checkbox (or even 4th and 5th), the cookie stores them as pro1 and pro2 and so on. So it's starting at 1 and going down rather than storing the name of the box I actually click.


  • 2. If I go back and reselect different boxes, it doesn't overwrite the cookie. Instead the alert displays my first selection.


  • 3. If I try to use textboxes it breaks ?


  • But i'm trying to fix all that.. Might take me a while. Javascript&me=newb!! ?
    Copy linkTweet thisAlerts:
    @bals28mjkOct 11.2007 — 1. If I click the 2nd and 3rd checkbox (or even 4th and 5th), the cookie stores them as pro1 and pro2 and so on. So it's starting at 1 and going down rather than storing the name of the box I actually click.[/QUOTE]That is a matter of personal preference. If you want a different name (same name as the input elements) change line 20 to cName[i]=el[i].name. 2. If I go back and reselect different boxes, it doesn't overwrite the cookie. Instead the alert displays my first selection.[/QUOTE]That was never part of your question? They are stored as cookies and will be until a month from now, unless of course you change the expiration date.3. If I try to use textboxes it breaks [/QUOTE]Yes. The form is restricted for simplicity. If you know any CSS you can position your texboxes wherever you want.



    If you're still lost:

    [URL=http://www.quirksmode.org/js/cookies.html]cookies[/URL]

    [URL=http://sideways8.files.wordpress.com/2006/08/cookiemonster_1.jpg]No more cookies?[/URL]<-- Very helpful

    [URL=http://www.w3schools.com/js/js_cookies.asp]Some more cookies[/URL]
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 11.2007 — Sorry, don't get me wrong, I wasn't trying to say it was a fault in your script! ? Your script was spot on, I just need to modify it to suit my needs.

    Thanks for the help once again. I'll check out those resources and see if I can get it working to my needs.
    Copy linkTweet thisAlerts:
    @bals28mjkOct 11.2007 — Check the second link right now! It's serious.
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 11.2007 — Hahaha ?

    Well i've pretty much got everything working now ? Cookies are starting to make a bit more sense.

    However i've just decided I need to use text boxes rather than checkboxes (so uses can input a quantity).. Is it easy enough to change the code to suit?

    Also is there a way to store all the data in one cookie? Or is it better to store each product in a different cookie?
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 11.2007 — Also, the script saves a cookie with the value "undefined" for the checkboxes I do not select. Is there a way to stop this?

    (Sorry to be a pain :o )
    Copy linkTweet thisAlerts:
    @bals28mjkOct 11.2007 — Oh no, you found a flaw.
    [CODE]
    for(var i=0,j=0;i<l;i++)
    {
    if(el[i].checked)
    {
    cValue[j]=el[i].value
    cName[j]=el[i].name
    }
    }
    [/CODE]
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 11.2007 — Hmm i'm actually having a lot of trouble now.

    I incorporated the script into my product catalog, and it's not working too well. I added 6 mock-up products to try it out. If I click all 6 it only saves 2 or 3 of them. Sometimes it only stores 1. And sometimes if I click 2 or 3 it only saves 1 of them.

    Strange? Is the script not made to handle more than a few items?
    Copy linkTweet thisAlerts:
    @bals28mjkOct 11.2007 — I forgot to increment j.[CODE]for(var i=0,j=0;i<l;i++)
    {
    if(el[i].checked)
    {
    cValue[j]=el[i].value
    cName[j]=el[i].name
    j++
    }
    }[/CODE]
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 11.2007 — Perfect ?

    I think i'll try and solve the text boxes issue myself just so I know I can do it ?

    Thanks once again for all your help! ?
    Copy linkTweet thisAlerts:
    @ReckonerauthorOct 12.2007 — Another question -

    When I go to retrieve the cookie, what do I set the cookie name to?

    I.e. on the line "cookie_name = "name";"

    As my cookie names are variable..
    Copy linkTweet thisAlerts:
    @bals28mjkOct 12.2007 — If you haven't already, I advise you give the links a look.
    ×

    Success!

    Help @Reckoner 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 6.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: @nearjob,
    tipped: article
    amount: 1000 SATS,

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

    tipper: @meenaratha,
    tipped: article
    amount: 1000 SATS,
    )...