0

I'm trying to set cookies in an easy code example, but they don't work as I expect. The problem is that the code doesn't work, it never says "Welcome again Nemo!" Can you help me please? What i am doing wrong? Thank you very much for your time!!!

  <script>

        function getCookie() {

            var name = document.cookie.split('=')
            if (name[1] != "" && name[1] != null){
                return name[1];
            }else{
                return "";
            }
        }

        function checkCookie() {
            var username=getCookie();
            if (username!="") {
                alert("Welcome again " + username);
            }
            else{
                username = prompt("Please enter your name:");
                if (username != "" && username != null) {
                    document.cookie =  "Username=" + username;
                }
            }
        }

        checkCookie();

    </script>
1
  • 1
    document.cookie doesn't give back exactly what you assign to it. Retrieving its value will give you a string with all accessible cookie names/values delimited by semicolons. Commented Feb 15, 2015 at 17:37

1 Answer 1

2

Are you trying to use cookies in a local file using chrome? It's not allowed, see: How to read/write cookies for local file:/// HTML document? and Why does Chrome ignore local jQuery cookies?

Sign up to request clarification or add additional context in comments.

3 Comments

S/He has to use a web server, whether a local or online one :)
Oh my god it was driving me crazy, thank you very much, I've tried with FireFox and its working fine, thank you really really much!
Your welcome. Also take the @jonathan-lonowski comment to get your code working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.