tags:

views:

1546

answers:

4

some body help me. how to create, read, and erase some cookies with jquery

+2  A: 

jquery plug in

http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

Haim Evgi
there is always a plug in somewhere :) but instead of loading more plugins, I do prefer the "normal" version ;)
balexandre
A: 

As I know, there is no direct support, but you can use plain-ol' javascript for that:

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

            var fixedName = '<%= Request["formName"] %>';
            name = fixedName + name;

            document.cookie = name + "=" + value + expires + "; path=/";
        }

        function readCookie(name) {
            var nameEQ = 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 c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function eraseCookie(name) {
            createCookie(name, "", -1);
        }
balexandre
question is "with jquery"
Natrium
i have been use this script, but doesn't work
Agus Puryanto
@Natrium and my answer states (first line!) that there is no Core functions to deal with it
balexandre
@Agus ... works fine here, I have it in production projects and they work like a charm! what error are you getting?
balexandre
That code isn't really plain old JavaScript. The part that says `<%= Request["formName"] %>` shows that this is intended to be pre-processed by a C# ASP.NET page. Delete the two lines that mention `fixedName` and it might work elsewhere.
Daniel Earwicker
+1  A: 

Use COOKIE plugin:

Set a cookie

$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

alert( $.cookie("example") );

Delete the cookie

$.cookie("example", null);
Ramesh Soni