4

When a user click on a button it would take them to a link but before they go to that link, the cookie will need to be set to either English (EN) or French (FR). I got an example here: http://www.quirksmode.org/js/cookies.html

but for some reason, it's not reading in the cookie and I'm not sure where I'm going wrong. This is what I have:

<!DOCTYPE html>
<html>
<body>

<p>This is for the Browser Cookies.</p>

<button onclick="EN_Cookie()">English Link</button>  <button onclick="FR_Cookie()">French Link</button>


<script>
function EN_Cookie() {  
    setCookie("SMDCookie","EN",7);
    //location.href = 'https://google.com';
}

function FR_Cookie() {
   setCookie("SMDCookie","FR",7);
   //location.href = 'https://google.com';
}

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

</script>

</body>
</html>

Any suggestions??

user1736786
  • 139
  • 1
  • 4
  • 11

2 Answers2

0

I reviewed your code and found your set cookie function is correct. May be your getCookie not working, i am sharing get cookie function:

  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 "";
 }
harsh_apache
  • 433
  • 4
  • 10
0

Here are functions you can use for creating and retrieving cookies

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

Copied from How do I create and read a value from cookie with javascript?

miken32
  • 42,008
  • 16
  • 111
  • 154
Mohit Kumar Gupta
  • 362
  • 1
  • 6
  • 21