Cloudboy22
Cloudboy22

Reputation: 1514

Cookie is not set properly

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.

Upvotes: 1

Views: 79

Answers (1)

Alex35
Alex35

Reputation: 73

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.

Upvotes: 1

Related Questions