22

I want to:

  1. Check to see if a cookie with name of "query" exists
  2. If yes, then do nothing
  3. If no, create a cookie "query" with a value of 1

Note: I am using jQuery 1.4.2 and the jQuery cookie plugin.

Does anyone have any suggestions as to how I can do this?

BryanH
  • 5,826
  • 3
  • 34
  • 47
Sphvn
  • 5,247
  • 8
  • 39
  • 57

3 Answers3

49
if($.cookie('query') === null) { 
    $.cookie('query', '1', {expires:7, path:'/'});
}

Alternatively, you could write a wrapper function for this:

jQuery.lazyCookie = function() {
   if(jQuery.cookie(arguments[0]) !== null) return;
   jQuery.cookie.apply(this, arguments);
};

Then you'd only need to write this in your client code:

$.lazyCookie('query', '1', {expires:7, path:'/'});
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
6

Similar to Jacobs answer but I prefer to test for undefined.

if($.cookie('query') == undefined){
    $.cookie('query', 1, { expires: 1 });
}
Colin Bacon
  • 15,436
  • 7
  • 52
  • 72
  • 1
    With the latest update from the script, `null` is now deprecated and `undefined` must be used. – Warface Aug 29 '13 at 12:13
  • Why do you say that 'null' is now deprecated? I was not able to find any supporting material on this online. See [here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features). – rodiwa Sep 22 '15 at 04:04
6

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 Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • @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 Gallarde May 13 '10 at 02:16