title: How to overwrite Cookie Value in Javascript with a button onclick?
body: <p>I'm trying to overwrite a cookie value when a user clicks on a button and using Javascript. I want to replace a default cookie value with the new value from the button onclick. I tried to follow the tutorial here: <a href="https://www.quirksmode.org/js/cookies.html" rel="nofollow noreferrer">https://www.quirksmode.org/js/cookies.html</a> But it doesn't really go into the details about the actual buttons/hyperlinks' functionality. It looks like he was able to update/overwrite a cookie just with the createCookie function, but no matter what I try to do it doesn't work. Here is my code below:</p>
  
  <pre><code>&lt;script&gt;
  
  function createCookie(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=/";
  }
  
  function readCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i &lt; ca.length;i++) {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
  }
  
  
  document.cookie = "sbhlocation_city=Muncie";
  document.cookie = "sbhlocation_state=IN";
  
  
  var setLocationCity = document.cookie.replace(/(?:(?:^|.*;\s*)sbhlocation_city\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  var setLocationState = document.cookie.replace(/(?:(?:^|.*;\s*)sbhlocation_state\s*\=\s*([^;]*).*$)|^.*$/, "$1");
  
  
  &lt;/script&gt;
  
  &lt;p class="body-text"&gt;
  &lt;script&gt;
  document.write(setLocationCity);
  &lt;/script&gt;
  &lt;/p&gt;
  
  &lt;p class="body-text"&gt;
  &lt;script&gt;
  document.write(setLocationState);
  &lt;/script&gt;
  &lt;/p&gt;
  
  &lt;button onclick="createCookie('sbhlocation_city','Waco',365)" href="#"&gt;Set City to Waco&lt;/button&gt;
  </code></pre>
  
  <p>The Default cookie value for City should be Muncie, but the button onlick needs to change the cookie value for City to Waco. When I try it, the city does not update. I'm very new to Javascript so any help is much appreciated. Thanks!</p>