views:

432

answers:

2

TLDR: Want to check if cookie exists, if it doesn't create it.


Am using jquery1.4.2 and jquery cookie,

I know this is probably very simple but I just cant get my head right at the moment.

I want to:

  1. Check to see if a cookie with name of "query" exists
  2. If so nothing.
  3. If not create a cookie "query" with a value of 1.

But only if it doesn't already exist.

Thanks in advance

+5  A: 
if( $.cookie('query') == null ) { 
    $.cookie( 'query', '1',  { expires: 7, path: '/' } );
}
Jacob Relkin
That's what I have tried. Not creating it :S
Thqr
!= to == and will accept your answer soon as it lets me :P
Thqr
@Jacob Relkin - i think `!=` should be `==` :p
Reigel
@Ozaki, Did it work?
Jacob Relkin
Yeah worked. Needed to give my brain a kickstart. lol
Thqr
+1  A: 

this??

$.cookie('query', '1'); //sets to 1...
$.cookie('query', null); // delete it...
$.cookie('query'); //gets the value....

if ($.cookie('query') == null){ //Check to see if a cookie with name of "query" exists
  $.cookie('query', '1'); //If not create a cookie "query" with a value of 1.
} // If so nothing.

what more do you want??

Reigel
MM It can be user defined on another page. But if it is not (so doesn't exist at all) I want to create it with a default value. This would create and delete it.
Thqr
Did not want to set and delete then check the value then do the IF statement. Thanks for the help though.
Thqr
@Ozaki - I 'm guessing you misunderstood it... what I'm trying to show are the possible options... well I'm glad you solved it now... :) cheers!
Reigel
@Reigel yeah sorry I was a bit vague as well.
Thqr