StevenR
StevenR

Reputation: 445

Saving Cookie with Javascript

Looking to create a cookie where it holds the name of the person looking to take a quiz.

It will ask for the user when the page loads, but it doesn't remember the cookie when I reload the browser.

Anyone have any idea why?

Sorry, I know it is a really basic question. Trying to teach myself about cookies with Javascript.

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<style>
h1, h2{
    margin-top: 150px;
    text-align: center;
    font-family: Arial, Helvetica, sans-serif;
}
p {
    margin-bottom:0px;
    text-align: center;
}
.button {
    padding: 20px 20px;
    border-radius: 15px;
    font-size: 14px;
    cursor: pointer;
    margin-left: 100px;
    margin-top: 50px;

}
#banner{
     padding:0 145px;
}
#banner img{
     display:block;
     margin:0 auto;
}
div.buttonGroup{
    margin-left: 450px;
}
body {
    background-color:#ffdab3;
}
</style>
<meta charset="UTF-8">
</head>

<body onload checkCookies()>

<script>
function setCookie(cname, cvalue, exdays) {

    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue  +";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}
</script>
</body>
</html>

Upvotes: 4

Views: 56

Answers (1)

blancVector
blancVector

Reputation: 23

@raul.vila don't load the page in a static manner (try with a local server). It would work then

Upvotes: 2

Related Questions