Search code examples
javascriptcookiescheckboxsetcookie

Getting a checkbox to write a JavaScript cookie


I've got a page with a splash screen, where users select one of two languages in which the rest of the site will be displayed. Next to each language option is a "remember my choice", HTML form, checkbox. How can I have the selected checkbox write a cookie with the language preference, which would skip the splash screen on future visits?


Solution

  • May be you can use something like below, Note code not tested:

        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
      function setCookie(c_name,value,expiredays) {
            var exdate=new Date()
            exdate.setDate(exdate.getDate()+expiredays)
            document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate)
        }
    
        function getCookie(c_name) {
            if (document.cookie.length>0) {
                c_start=document.cookie.indexOf(c_name + "=")
                if (c_start!=-1) { 
                    c_start=c_start + c_name.length+1 
                    c_end=document.cookie.indexOf(";",c_start)
                    if (c_end==-1) c_end=document.cookie.length
                        return unescape(document.cookie.substring(c_start,c_end))
                } 
            }
            return null
        }
    onload=function(){
    document.getElementById('linksNewWindow').checked = getCookie('linksNewWindow')==1? true : false;
    }
    function set_check(){
    setCookie('linksNewWindow', document.getElementById('linksNewWindow').checked? 1 : 0, 100);
    }
    </script>
    </head>
    <body>
    <div>Hi</div>
    <input type="checkbox" id="linksNewWindow" onchange="set_check();">
    </body>
    </html>