Function - How to stop a variable from being destroyed on pressing F5 in javascript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have the following code

<html>
    <head>
        <script>
            var m=0;
            function add() {
                m++;
            }
        </script>
    </head>
    <body>
        <button onclick="add();">click</button>
    </body>
</html>  

But if I refresh the page then again the value of m starts from 0. How can I persist the value of m between each load of the page on a client machine?

Answers

you can use cookies from javascript. check this link.

http://www.w3schools.com/js/js_cookies.asp http://www.w3schools.com/js/js_cookies.asp

here is the working code sample:

<html> 
<head> 
<script> 
var m=getCookie("m");
if(isNaN(m)) {
    m=0;
}
function add() 
{
    m++;
    alert(m);
    setCookie("m",m,86400);
} 

function setCookie(c_name,value,exdays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^s+|s+$/g,"");
    if (x==c_name)
    {
            return unescape(y);
        }
    }
}
</script> 
<body>
<button onclick="add();">click</button> 
</body> 
</html> 

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/7684299/how-to-stop-a-variable-from-being-destroyed-on-pressing-f5-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils