简体   繁体   中英

how to read and delete a Cookie with javascript?

allCookies contents a list of my Browser Cookies. I want to delete Cookies with this function delCookie(), but It just delete the first Cookie, and not the others cookies. And how could i do to update a cookie???

<input type="button" value="DElete" onclick="delCookie()">
    <input type="button" value="Update" onclick="modCookie()">


<select multiple id="allCookies" size="5">
        <!-- Cookies content-->
    </select><br>

 function delCookie() {
    if (confirm('Are u sure?')) {
        var e = document.getElementById("allCookies");
        var strUser = e.options[e.selectedIndex].value;
        document.cookie = encodeURIComponent(strUser) + "=deleted; expires=" + new Date(0).toUTCString();
    }
}

It just delete the first Cookie, and not the others cookies.

The selectedIndex property of a <select> element only returns the index of the first selected option. To check all of them in a multiple select, you will need to iterate the options collection:

var os = document.getElementById("allCookies").options;
for (var i=0; i<os.length; i++) {
    if (os[i].selected) {
        var strUser = os[i].value;
        …
    }
}

And how could i do to update a cookie???

Just overwrite the cookie, ie use the same method as when creating them.

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