![Snoopli: Your Intelligent AI Search Engine for Reliable Answers](/assets/images/robot.webp?v=1.35)
How do I set and unset a cookie using jQuery, for example create a cookie named 'someName' and set its value to 'someValue'?
To set and unset cookies using jQuery, you need to use the jQuery Cookie plugin. Here's how you can create, read, and delete cookies:
Setting a Cookie
To set a cookie named 'someName'
with the value 'someValue'
, you can use the following code:
$.cookie('someName', 'someValue');
This will create a session cookie that expires when the browser session ends. If you want to set an expiration date, you can add an options object:
$.cookie('someName', 'someValue', { expires: 7 }); // Expires in 7 days
Unsetting (Deleting) a Cookie
To delete a cookie, you pass null
as the value and ensure you use the same path and domain as when the cookie was set:
$.removeCookie('someName');
If the cookie was set with specific options (like path or domain), you need to include those options when deleting it:
$.removeCookie('someName', { path: '/' }); // Assuming it was set with path '/'
Reading a Cookie
To read the value of a cookie, you simply pass the cookie name:
var cookieValue = $.cookie('someName');
This will return the value of the cookie if it exists, or undefined
if it doesn't.
Example Usage
Here's a complete example that includes setting, reading, and deleting a cookie:
// Set a cookie
$.cookie('someName', 'someValue', { expires: 7 });
// Read a cookie
var cookieValue = $.cookie('someName');
console.log(cookieValue); // Outputs: someValue
// Delete a cookie
$.removeCookie('someName');
Make sure to include the jQuery Cookie plugin in your HTML file before using these methods:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Important Notes
- Path and Domain: When setting and deleting cookies, ensure you use the same path and domain to avoid issues with cookie accessibility.
-
Secure Cookies: To set secure cookies (sent only over HTTPS), use the
secure
option:$.cookie('someName', 'someValue', { secure: true });
- Expiration: The
expires
option sets the number of days until the cookie expires. Use a negative value to delete a cookie immediately.