How do I set and unset a cookie using jQuery, for example create a cookie named test and set the value to 1?
In jQuery, you can set and unset cookies using the $.cookie()
method provided by the jQuery Cookie plugin. Here's how you can create a cookie named "test" with the value "1" and then unset (remove) the cookie:
- Setting a Cookie:
html
<!-- Include jQuery and the jQuery Cookie plugin -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
$(document).ready(function() {
// Set a cookie named "test" with the value "1" and an expiration of 7 days
$.cookie('test', '1', { expires: 7 });
console.log("Cookie set:", $.cookie('test')); // Output: 1
});
</script>
- Unsetting (Removing) a Cookie:
html
<!-- Include jQuery and the jQuery Cookie plugin -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
$(document).ready(function() {
// Unset (remove) the cookie named "test"
$.removeCookie('test');
console.log("Cookie unset:", $.cookie('test')); // Output: undefined
});
</script>
In both examples, the jQuery Cookie plugin provides the $.cookie()
method to set and get cookie values and the $.removeCookie()
method to remove cookies. Make sure to include jQuery and the jQuery Cookie plugin in your HTML before using these methods.
Please note that the jQuery Cookie plugin is not actively maintained and might not be the best choice for managing cookies in modern web development. Consider using the document.cookie
property or more modern libraries for working with cookies.
Comments
Post a Comment