Displaying cookie + message w/ JavaScript

I’m new JavaScript and looking for some help with cookies. What would be the most simple way of setting and retrieving a cookie from a prompt and then displaying a message with that cookie in an html element. Here is what I have so far but cant seem to display the message.

Thank you!

<!DOCTYPE html>
<html lang="en">
<head>
    <script>

        function setCookie(cname,cvalue,exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires=" + d.toGMTString();
            document.cookie = cname+"="+cvalue+"; "+expires;
        }

        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for(var i=0; i<ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        }

        function checkCookie() {
            var user=getCookie("username");
            if (user != "") {
                document.getElementById("welcome").innerHTML = username;
            } else {
                user = prompt("Please enter your name:","");
                if (user != "" && user != null) {
                    setCookie("username", user, 30);
                }
            }
        }
    </script>

</head>
<body onload="checkCookie()">

<p id="welcome"> <!-- want "Welcome again" + username message here --> </p>

</body>
</html>

You don’t use cookies with prompt() - prompt() was used for debugging in the days before console.log() was introduced - you shouldn’t be using prompt for debugging any more (and its use for anything other than debugging was dead when Netscape 4 ceased to be used).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.