ajc2000
ajc2000

Reputation: 834

I can only make a cookie have one value in javascript

I have recently taken on a concept new to me in Web Development: cookies.

I understand that when you assign document.cookie a value, you are essentially creating a string.

However, when I run this simple code:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body onLoad="makeCookie()">
        <script>
            function makeCookie(){
                document.cookie = "value=4; pi=3.14"
                alert(document.cookie);
            }
        </script>
    </body>
</html>

It alerts "value=4" instead of the "value=4; pi=3.14;" that I want it to alert.

How can I fix this, or, are there any easier alternatives to storing data even when the user leaves the page in JavaScript?

Upvotes: 1

Views: 450

Answers (1)

Barmar
Barmar

Reputation: 782693

You can only set one cookie at a time. To assign multiple cookies, do separate assignments:

function makeCookie() {
  document.cookie = "value=4";
  document.cookie = "pi=3.14";
  alert(document.cookie);
}

Within a cookie assignment, ; is used to add optional attributes, e.g.

document.cookie = "value=4; max-age=900";

DEMO

Upvotes: 3

Related Questions