Pregunta

I am using this jquery.cookie plugin and I need to set value to TRUE or NULL/FALSE.

I am trying to do it like this: $.cookie('ff', true, { expires: 30, path: '/' }); but it sets the value to string and not boolean.

Any ways of fixing this?

¿Fue útil?

Solución

Cookies are only string-valued. As gdoron commented, if you want to treat the value as a boolean, you need to parse it back to a boolean when the cookie value is read back out.

Since you commented that you are reading the cookie value with PHP, see Parsing a string into a boolean value in PHP.

Otros consejos

Client side:

$.cookie('ff', "true", { expires: 30, path: '/' });

Server side:

$cookie = $this->input->cookie() == "true";

EDIT: Cookies are strings. Anything stored to cookies will need to be converted to strings. Hence you have to do the string to boolean conversion on the reading side of it. Above I have put an example for PHP (CodeIgniter).

If you are just looking to use a cookie as a sort of flag, then just check if the cookie exists and if it does not you can assume it is false:

const isSet = Boolean(cookie.get('my-cookie')) || false

This way you don't need to even worry about the actual value of the cookie and just whether or not it exists.

Another way to do this is

var mycookie = !($.cookie("cookiename")=='false')

Or:

if(!($.cookie("cookiename")=='false')){ 
    //mycode 
}

If the value is 'false' then ($.cookie("cookiename")=='false') will return true so we invert it by using ! which return false

if the value is not 'false' then it will return false so we invert it by using ! which return false

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top