ReynierPM
ReynierPM

Reputation: 18690

How to set/read the value of a cookie using jQuery Cookie plugin

I'm trying to set the value of a cookie using jQuery Cookie plugin and is not working since all the time the code goes though the "Cookie not set" alert. I'm using latest jQuery Cookie release and also jQuery 2.1.1. This is how I'm doing:

// HTML
<button id="btnSetCookie">Set</button>
<button id="btnUnSetCookie">Unset</button>
<button id="btnShow">Show cookie status/val</button>

// jQuery
$(document).ready(function() {
    $("#btnSetCookie").on('click', function(){
        $.cookie('cookieVal', true);
    });

    $("#btnUnSetCookie").on('click', function(){
        $.cookie('cookieVal', false);
    });

    $("#btnShow").on('click', function(){
        var cook = $.cookie('cookieVal');

        if (cook === true)
            alert("Cookie TRUE");
        else if (cook === false)
            alert("Cookie FALSE");
        else
            alert("Cookie not set");
    });
});

I've try also comparing cook with == only and not working since I get the same result, I'm doing something wrong? I made this Fiddle with the same code just for play with it. Can any give some help or tell what can be wrong there?

As an additional question/doubt, if I set the cookie on click event and then move between steps on a wizard where the form is not send yet to any place, it will be set until I move away from this page or until the user clean it's cookies, right?

Upvotes: 0

Views: 993

Answers (1)

Simon Sch&#228;rer
Simon Sch&#228;rer

Reputation: 602

you can not use boolean values. Use a string instead:

$(document).ready(function() {
$("#btnSetCookie").on('click', function(){
    $.cookie('cookieVal', "true");
});

$("#btnUnSetCookie").on('click', function(){
    $.cookie('cookieVal', "false");
});

$("#btnShow").on('click', function(){
    var cook = $.cookie('cookieVal');

    if (cook === "true")
        alert("Cookie TRUE");
    else if (cook === "false")
        alert("Cookie FALSE");
    else
        alert("Cookie not set");
});

});

Upvotes: 1

Related Questions