1

newbie here. Trying to create a cookie like this

    function setCook()
{
    var name=prompt("enter your name");
    document.cookie=name;
    var mycookie = document.cookie,
    fixed_cookie = decodeURIComponent(mycookie);

}
function getCookie()
{

    var mycookie = fixed_cookie;
    document.write(mycookie);
}

setCook();
getCookie();

But somehow the document is blank. Please tell me where i am doing it wrong. Thanks.

Cloudboy22
  • 1,496
  • 5
  • 21
  • 39
  • You placed a `,`, instead of a `;` in the `var mycookie = document.cookie,` line. Placing the `;` will make it an implicit global, but that's not so good, it'd be better if you declared `fixed_cookie` outside of both functions, or if you did: `window.fixed_cookie`. Also, `document.cookie` returns all of the cookies related to the document, I don't know if you want that. –  May 26 '15 at 02:45

1 Answers1

1

The short answer: Try the following:

function setCook()
{
    var name=prompt("enter your name");
    document.cookie="mycookie="+name+"; path=\";
}

Explanation

A document can actually have multiple cookies, so cookies are given names.

To set a cookie named "mycookie", you would do this:

document.cookie = "mycookie=some value";

You can also set multiple cookies at once like this:

document.cookie = "mycookie1=value1; mycookie2=value2; mycookie3=value3";

Also, you should note that document.cookie is not just a standard property, but rather a getter and setter. To illustrate this:

document.cookie = "mycookie=this is mine";
document.cookie = "yourcookie=this is yours";

// alert is: mycookie=this is mine; yourcookie=this is yours
window.alert(document.cookie);

Hopefully this should get you started. Please look at Set cookie and get cookie with JavaScript.

Community
  • 1
  • 1
Alex35
  • 73
  • 1
  • 5
  • jfriend00 is right on point that accessing document.cookie gives all the cookies for the document. You would need to parse the string to extract the value for a single cookie. This is why frameworks such as jQuery provide utility functions to work with cookies that abstract these details away. – Alex35 May 26 '15 at 03:15
  • 1
    EDIT: I missed the `,`. Therefore my comment below is moot. As a result of the `,`, `fixed_cookie` is declared as a local variable after all! This is because multiple variables can be declared in one statement (e.g. `var var1="a", var2="b", var3="c";`). My original comment follows: By the way, in response to @jfriend00, fixed_cookie is not a local variable! Local variables are usually declared var myvariable = "some value"; however, when a variable is declared without the word var, it implicitly becomes a property of the window object, and all properties of window are global. – Alex35 May 26 '15 at 03:19