How to set, unset and get cookie in jQuery?
author
,
Fond of IT

Is there a way to set and get cookie in jQuery, please explain and help us to achieve this requirement. 

  • Total 1 Answer
  • 111
Can You answer this question?
author
,
Fond of IT

You can set, get and delete cookie in jQuery using a jquery plugin. This plugin is very useful, easy to use in any website and get the requirement done without any hassle. Follow below steps and your are good to go:

1- Include the below library in the file and use as below mentioned.

<script src="/path/to/jquery.cookie.js"></script>

2- Usage:

Create session cookie:

$.cookie('name', 'value');

Create expiring cookie, 7 days from then:

$.cookie('name', 'value', { expires: 7 });

Create expiring cookie, valid across entire site:

$.cookie('name', 'value', { expires: 7, path: '/' });

Read cookie:

$.cookie('name'); // => "value" $.cookie('nothing'); // => undefined

Read all available cookies:

$.cookie(); // => { "name": "value" }

Delete cookie:

// Returns true when cookie was successfully deleted, otherwise false $.removeCookie('name'); // => true $.removeCookie('nothing'); // => false // Need to use the same attributes (path, domain) as what the cookie was written with $.cookie('name', 'value', { path: '/' }); // This won't work! $.removeCookie('name'); // => false // This will work! $.removeCookie('name', { path: '/' }); // => true

Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is.

You can find the plugin from below URL:

https://github.com/carhartl/jquery-cookie