简体   繁体   中英

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".

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 .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM