ryan
ryan

Reputation: 55

Need Help in Creating a Cookie

I have a button named yes and another named no.

<input type="button" name="yes" onclick="button()">
<input type="button" name="no">

I want to create a cookie when yes is clicked that would store the info "YES" and needs to expire after 7 days. How do i do that? The only information that the cookie needs to store is "YES".

Upvotes: 2

Views: 190

Answers (2)

Robert
Robert

Reputation: 21388

Here's what i use

var cookie = {
    "create": function(name, value, days) {
        if (typeof days !== 'number' || typeof name !== 'string' || typeof value !== 'string') {
            return false;
        }
        var date = new Date();
        date.setTime(date.getTime() + (days*86400000));
        document.cookie = name + '=' + value + '; expires=' + date.toGMTString() + '; path=/';
    },
    "read": function(name) {
        var cookie = document.cookie,
            i, val = false;
        cookie = cookie.split(';');
        for (i = 0; i < cookie.length; i++) {
            if (cookie[i].indexOf(name) !== -1) {
                while (cookie[i].indexOf(name) > 0 && cookie[i].length > name.length) {
                    cookie[i] = cookie[i].substr(1);
                }
                val = cookie[i].substr(name.length + 1);
            }
        }
        return val;
    },
    "erase": function(name) {
        this.create(name, '', -1);
    }
};

You can then use:

cookie.create("userName", "Bill", 7); // store userName "Bill" for 7 days.

cookie.read("userName"); // "Bill"

cookie.erase("userName"); 

Here's a fiddle to see how it works. http://jsfiddle.net/robert/4vLT6/

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could use document.cookie:

var expDate = new Date();
expDate.setDate(expDate.getDate() + 7);
document.cookie = 'your_cookie_name=YES;expires=' + expDate.toUTCString();

Or if you are using jquery you may take a look at the Cookie plugin. Here's an example.

Upvotes: 3

Related Questions