How do i Set, Read & Delete cookie using jQuery?

How do i Set, Read & Delete cookie using jQuery
620 Views
3.2
(215)

You can Set, Read and Delete cookie using jQuery below with code.

function cxc_createCookie( name, value, days ) {
	var expires;
	if( days ) {
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		expires = "; expires=" + date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function cxc_readCookie( name ) {
	var nameEQ = encodeURIComponent(name) + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
		if( c.indexOf(nameEQ) === 0 ){ return decodeURIComponent(c.substring(nameEQ.length, c.length)); }
	}
	return null;
}

function cxc_eraseCookie( name ) {
	cxc_createCookie( name, "", -1 );
}

Set, Read and Delete cookie function using jQuery like below code.

jQuery(document).ready(function(){
	cxc_createCookie( 'CookieName', 'CookieValue', 'Cookiedays' ); //Set Cookie
	cxc_readCookie( 'CookieName' ); // Read Cookie
	cxc_eraseCookie( 'CookieName' ); // Delete Cookie
});

How would you remove cookies in jQuery?

Please follow the steps given in the blog.

Can we manually set cookies?

However, there may be situations when you need to manually set a cookie. For example, you may be testing a site that requires authentication but without really conducting the authentication in the script. Instead of logging in, you might manually configure the cookies that would normally be generated.

How useful was this blog?

Click on a star to rate it!

Average rating 3.2 / 5. Vote count: 215

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *