0

I have a button that when clicked should delete a cookie, call a function that collects a value from a textbox and save it as the new cookie value.

The problem I'm having is that after the button is clicked, the function is executing as if there was a value in the cookie.

I've logged the value of the cookie and it's showing null. Why isn't my function finding that the value is null?

//when new player is pressed
$('#BtnPlayAsNew').button().click(function () {
    $.cookie('name', null); //delete cookie

    $('#Result').hide();
    getUsername(); //call function 
});

function getUsername() {
    //get cookie 
    var cookie = $.cookie('name');
    //check value of cookie
    if (cookie == null || cookie == "") {
        $('#controls').hide();
        $('#NewUser').show();
        $('#BtnUser').click(function () {
            name=$('#tbUser').val();
            $.cookie('name', name,{path:'/' });
            $('#NewUser').hide();
            $('#controls').show();
        });
    }else{
        $('#NewUser').hide();
        $('#controls').show();
    }
}
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
exeleon
  • 121
  • 2
  • 14
  • You are using an outdated version of jquery-cookie. Access https://github.com/js-cookie/js-cookie/releases, get the first version and read the docs of the specific version/tag you want. As @Samurai pointed out, the `null` argument for removal was deprecated and removed months ago. – Fagner Brack May 08 '15 at 19:19

1 Answers1

1

$.cookie('name', null); does NOT remove the cookie, it assigns string "null" to it, you can check it by console.log(cookie == "null"); which gives true. Instead you can use javascript's cookie with expiration date set on the past. So to set cookie null use this instead:

document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
Samurai
  • 3,724
  • 5
  • 27
  • 39