If cookies exist...

Discussion in 'JavaScript' started by Lordo, Sep 23, 2006.

  1. #1
    A noob here :)
    How can I check if a cookie (cookie1 for example) exists or not. Should I directly use it and see if it equals "" or what?
    Also, where can I find a tutorial on how to use arrays in cookies?
     
    Lordo, Sep 23, 2006 IP
  2. Evoleto

    Evoleto Well-Known Member

    Messages:
    253
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Try to read the cookie, if it exists it will return its value, if not it will return a NULL value:

    
    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;
    }
    
    Code (markup):
    Source: http://www.quirksmode.org/js/cookies.html
     
    Evoleto, Sep 24, 2006 IP
  3. VONRAT

    VONRAT Banned

    Messages:
    181
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try searching for "javascript cookies" over search engines .. there are dozens of tutorials about them ..

    here is a simple parameter on how to set cookies

    document.cookie = "Name1=Value1; Name2=Value2; Name3=Value3";

    get the cookies by simply referencing document.cookie, it however return a string of which you can parse to get the cookie and value you want
     
    VONRAT, Sep 24, 2006 IP
  4. Lordo

    Lordo Well-Known Member

    Messages:
    2,082
    Likes Received:
    58
    Best Answers:
    0
    Trophy Points:
    190
    #4
    Thank you guys :)
     
    Lordo, Sep 24, 2006 IP