I have a page with several checkboxes. I check a few of them and go to the next page, when I come back on this page, these checkboxes need to remain checked as they were before navigating to another page. Need to do it with Javascript. Any clue??
3 Answers
If you're limited to JavaScript only and no server side language I think you are left to read/writing cookies to maintain the state. As others have referenced, server side technologies are much better at this but if you must:
JavaScript cookie sample code (reference: http://www.quirksmode.org/js/cookies.html) :
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 = "";
    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);
}
 
    
    - 29,308
- 20
- 68
- 109
You'll need to persist them between page-requests. You can use sessions or cookies to do this. What type of server are you working on, and with what type of server-side language?
Previous questions on SO have address writing/reading cookies from JavaScript.
I don't think there's any reasonably complicated way to do it without having any access to the server-side code, because at the minimum you need to install your code and also identify the HTML controls e.g. in order to check them. I 'm giving reasonable code that does what you want below.
Important notes:
- The code requires that each checkbox is given a distinct id attribute.
- The check state is stored in a cookie named 'JS_PERSISTENCE_COOKIE'. It would be better to store the name of this cookie in a variable instead of hardcoding it in a couple of separate places as I have done. What kind of variable should store the name depends on your app and requirements.
- It would be better to package the code inside an object instead of as a bunch of free functions as I have done. However, this is not relevant to your initial question.
- After clicking some checkboxes, you can simulate "navigating back to this page" by hitting CTRL+F5. F5 alone is not enough.
Here's the code and some sample HTML for testing:
<body onload="restorePersistedCheckBoxes()">
    <input type="checkbox" id="check1" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check2" onclick="persistCheckBox(this)" />
    <input type="checkbox" id="check3" onclick="persistCheckBox(this)" />
    <input type="button" value="Check cookie" 
           onclick="alert(document.cookie)" />
    <input type="button" value="Clear cookie"
           onclick="clearPersistenceCookie()" />
    <script type="text/javascript">
        // This function reads the cookie and checks/unchecks all elements
        // that have been stored inside. It will NOT mess with checkboxes 
        // whose state has not yet been recorded at all.
        function restorePersistedCheckBoxes() {
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                var el = document.getElementById(aPair[0]);
                if(el) {
                    el.checked = aPair[1] == '1';
                }
            }
        }
        // This function takes as input an input type="checkbox" element and
        // stores its check state in the persistence cookie. It is smart
        // enough to add or replace the state as appropriate, and not affect
        // the stored state of other checkboxes.    
        function persistCheckBox(el) {
            var found = false;
            var currentStateFragment = el.id + ':' + (el.checked ? '1' : '0');
            var aStatus = getPersistedCheckStatus();
            for(var i = 0; i < aStatus.length; i++) {
                var aPair = aStatus[i].split(':');
                if(aPair[0] == el.id) {
                    // State for this checkbox was already present; replace it
                    aStatus[i] = currentStateFragment;
                    found = true;
                    break;
                }
            }
            if(!found) {
                // State for this checkbox wasn't present; add it
                aStatus.push(currentStateFragment);
            }
            // Now that the array has our info stored, persist it
            setPersistedCheckStatus(aStatus);
        }
        // This function simply returns the checkbox persistence status as
        // an array of strings. "Hides" the fact that the data is stored
        // in a cookie.
        function getPersistedCheckStatus() {
            var stored = getPersistenceCookie();
            return stored.split(',');
        }
        // This function stores an array of strings that represents the 
        // checkbox persistence status. "Hides" the fact that the data is stored
        // in a cookie.
        function setPersistedCheckStatus(aStatus) {
            setPersistenceCookie(aStatus.join(','));
        }
        // Retrieve the value of the persistence cookie.
        function getPersistenceCookie()
        {
          // cookies are separated by semicolons
          var aCookie = document.cookie.split('; ');
          for (var i=0; i < aCookie.length; i++)
          {
            // a name/value pair (a crumb) is separated by an equal sign
            var aCrumb = aCookie[i].split('=');
            if ('JS_PERSISTENCE_COOKIE' == aCrumb[0]) 
              return unescape(aCrumb[1]);
          }
          return ''; // cookie does not exist
        }
        // Sets the value of the persistence cookie.
        // Does not affect other cookies that may be present.
        function setPersistenceCookie(sValue) {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' + escape(sValue);
        }
        // Removes the persistence cookie.
        function clearPersistenceCookie() {
            document.cookie = 'JS_PERSISTENCE_COOKIE=' +
                              ';expires=Fri, 31 Dec 1999 23:59:59 GMT;';
        }
    </script>
</body>
 
    
    - 428,835
- 81
- 738
- 806
 
     
    