pooja
pooja

Reputation: 58

How to set cookie in jquery?

I want to set cookie so that i get the value after refreshing the page.

I have written below code But i am not able to set the cookie.

$j("#add_to_cart_action").click(function(e) {
      $j.em.cart.addSelectedTitle();
    });

$j.em.cart.addSelectedTitle = function() {
  var addcartitemindx = $j("body").data("selected_title").product_id;
  var indx = $j("body").data("selected_title").cindex;
  var addcartitemtitle = $j("body").data("selected_title").ctitle;
  if ($j('input#chkout_'+addcartitemindx).length > 0) {
    alert('Shopping Cart Notification:\n "'+addcartitemtitle+'" is already added.');
    return false;
  }
  $j.cookie("example",addcartitemtitle);
  alert( $j.cookie("example") );
  //$j('#checkout_form ul').prepend('<li><input type="checkbox" id="chkout_'+addcartitemindx+'" class="added-item" value="'+addcartitemindx+'"/><a href="javascript:$j.em.cart.TriggerCartItem('+addcartitemindx+');">'+addcartitemtitle+'</a></li>');
  $j('#checkout_form ul').prepend('<li><input checked="true" type="checkbox" id="chkout_'+addcartitemindx+'" name="product[]" class="added-item" value="'+addcartitemindx+'"/><a href="javascript:$j.em.cart.TriggerCartItem('+indx+');">'+addcartitemtitle+'</a></li>');

  $j.em.cart.setCartDisplay();
};

Upvotes: 1

Views: 2864

Answers (3)

kioopi
kioopi

Reputation: 2250

You code looks fine to me. You can try to add options like this:

$.cookie('example', 'cookie-value', { path: '/', expires: 1 }); 

If that hasn't changed jquery.cookie is not in the core. Did you make sure to load the file? i.e.

<script src="js/jquery.cookie.js" type="text/javascript"></script>

Also cookies have to be enabled, obviously. You can see if your cookie gets set in ff 3.5 if you go to Tools->Preferences->Privacy and click on "remove individual cookies". There's a list of cookies ordered by domain.

Upvotes: 1

Lachlan McDonald
Lachlan McDonald

Reputation: 2424

Its worth noting that jQuery does not support cookies without the use of a third-party plug-in, as far as I can recall.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

To set a cookie in javascript:

document.cookie = 'name=value; expires=Thu, 1 Dec 2009 20:00:00 UTC; path=/'

Also there's a jquery plugin.

Upvotes: 1

Related Questions