简体   繁体   中英

How to overwrite Cookie Value in Javascript with a button onclick?

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: https://www.quirksmode.org/js/cookies.html 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:

<script>

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 < 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");


</script>

<p class="body-text">
<script>
document.write(setLocationCity);
</script>
</p>

<p class="body-text">
<script>
document.write(setLocationState);
</script>
</p>

<button onclick="createCookie('sbhlocation_city','Waco',365)" href="#">Set City to Waco</button>

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!

Try with this correction to your code:

<button onclick="createCookie('sbhlocation_city','Waco',365)" href="#">Set City to Waco</button>

The problem is "sbhlocation_city" is not a variable, is a text. And so is "Waco". Without the 'thisthingsaroundme' its taken as variable names. So it throws an "is undefined" error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM