Click here to Skip to main content
15,887,343 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Can you please give me an example code in JavaScript on how to keep the state of a checkbox by creating cookie when I refresh the page?

I have something as the following but I couldn't manage have it run as I expected. I am new in JavaScript.

/*** Simple interface to cookie ***/
Something.Cookie = function (cookieName, defaultValue) {
    function createCookie(name, value, days) {
        var expires = "";
        var date;
        if (days) {
            date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        var c;
        for (var i = 0; i < ca.length; i++) {
            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;
    }
    this.read = function () {
        var val = readCookie(cookieName);
        Something.log("Read " + val + " from cookie " + cookieName);
        return val;
    };
    this.readBoolean = function () {
        return this.read() === "true";
    };
    this.write = function (value) {
        createCookie(cookieName, value, 365);
    };
    this.writeBoolean = function (value) {
        value ? this.write("true") : this.write("false");
    };
    if (this.read() === null) {
        this.write(defaultValue);
    }
    return this;
};



Note:
onclick="GM_setValue("document.myform.mybox.value","true")
could also be a solution instead of using cookies.
However, GM_setValue cannot be called within onclick function.
A solution with GM_setValue would also be helpful because I mainly write this code in Greasemonkey.



Thanks,

Artug
Posted
Updated 9-Feb-11 16:07pm
v6
Comments
Sunasara Imdadhusen 10-Feb-11 0:07am    
Please confirm!

Do you have one check box and you have to maintain it's last state whenever you are visiting the page?

1 solution

I have multiple checkboxes on the page. I want to maintain their states every time I visit the page.

Thanks,
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900