Keep checkboxes checked even when page is reloaded using cookies

The following script uses cookies to do what you want. It will only work if cookies are enabled on the client machine and the browser is set to accept cookies. Private browsing may prevent it working. Other than that, the checkboxes are checked correctly on page re-load or on going to another page and returning. The expiry date for each cookie is set for one day. You can change this in the script variable called “tomorrow” if necessary.

The script assumes consistency in the ID of the checkbox <input> elements. For this example I have used CB1 - CB4. The regex looks for CB and one digit. If you want to change the id syntax you will need to change the regex pattern as well.

HTML
     <div id="checks">
        <input id="CB1" type="checkbox" value="ON">
        <input id="CB2" type="checkbox" value="ON"> 
etc .....

<script type="text/javascript">
var dcSplit, posnEq, firstGrp, lastGrp, posnCB, regEx, i=0;
 dcSplit=document.cookie.split("; ");
 regEx=(/CB\d=/);           
 for(i=0; i<dcSplit.length; i++)
  { posnEq = dcSplit[i].indexOf("=")+1;      
    posnCB=dcSplit[i].search(regEx);
    if(posnCB != -1)
      { firstGrp = dcSplit[i].substring(posnCB, posnEq-1);
        lastGrp = dcSplit[i].substring( posnEq, dcSplit[i].length);  
        document.getElementById(firstGrp).checked=eval(lastGrp);        
    }  }     
// ------
 var now=new Date(), tomorrow, allInputs, cookieStr;
 tomorrow=new Date((now.setDate(now.getDate())+(1*24*60*60*1000))).toGMTString(); 
 allInputs=document.getElementById("checks").getElementsByTagName("input");
 for(i=0; i<allInputs.length; i++){ allInputs[i].onclick=writeCookie; }
// --------   
 function writeCookie()
   { cookieStr=this.id+"="+this.checked+"; expires="+tomorrow+"; path=/";       
     document.cookie=cookieStr;
   } 
 // -------     
</script>

There is a working example on JSFiddle.