Cookies in jQuery with jQuery.Cookie library
In this
quick code you will learn how to read, write and delete session cookies using
jQuery. Remember to use jquery.cookie library on the page.
Creating Cookie
Here is
sample code to create cookie:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<input id="btnCreateCookie" type="submit" value="Create Cookie" />
<script>
$('#btnCreateCookie').click(function () {
$.cookie('cookieName', 'This is cookie value');
});
</script>
Here is
the cookie in the resource list, look at the screenshot.
Creating Cookie with expiry set 2 days
Here is
sample code to create cookie with expiry set 2 days.
$.cookie('cookieName', 'This is cookie value', { expires: 2 });
Creating Cookie which is valid across entire
website
Here is
sample code to create cookie which valid across entire website.
$.cookie('cookieName', 'This is cookie value', { expires: 2, path: '/' });
Read Cookie
To read
any cookie, just write following code:
$.cookie('cookieName');
If cookie
with this name does not exist, then you will see ‘undefined’ in the dialog. Look
at this screenshot which displays cookie result on screen.
Delete Cookie
To
delete any cookie, just write following code:
$.removeCookie('cookieName');
This returns
true when cookie was successfully deleted, otherwise false.
You can
try the code here on jsFiddle.
Hope
this helps.
Comments
Post a Comment