javascriptcookies

Clear cookies with javascript


I would like to ask some help here. I have an update form and when i submit i need to send back 2 values to the main page. (they contains a combobox index and a table rowindex so i could trigger them and would show me the selected item i have choose before submit. otherwise it selects the very first items) im using cookies for this and works well. the problem is that i cant clear the cookies. so after update it always loads the previous values when the document load.

i have the following:

document.cookie="data1="+variable1+"; path=/";
document.cookie="data2="+variable2+"; path=/";
//They holds the variables//

and when the page loads i get those data back:

$(document).ready(function() {

var x = document.cookie.split(';');

if ( x !== null) {
var x1 = x[0].split('=')[1];
var x2 = x[1].split('=')[1];
};

//i need a cookie clear function here then next time the page loads it would select the first items again//

I tried some already but none of them works:

1st:

 function clearListCookies(){
        var cookies = document.cookie.split(";");
            for (var i = 0; i < cookies.length; i++){   
                var clear =  cookies[i].split("=");
                document.cookie = clear[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";                                
            }
        }

2nd:

document.cookie = "data1=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; 
document.cookie = "data2=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

thanks for any help in advance


Solution

  • You need to specify path like so:

    document.cookie = "data1=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"; 
    document.cookie = "data2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
    

    Jsfiddle