0

I want to have a button which when you click on it adds 1 to a number, which is displayed on the screen. This is how far I got.

<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>

<script>
function addOne()
{
i++;
document.getElementById('inc').value = i;
}
</script>

How can I make it so that the number is saved into a cookie so whenever I come back the number is not changed back into 0?

  • possible duplicate of http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript – Rishi Php Apr 28 '14 at 10:07

1 Answers1

0

The variable i has no starting value. You could do the following:

updated, see http://jsfiddle.net/sUHy2/4/

<button onclick="addOne();">Click Me</button>
<input type="text" id="inc" value="0"></input>

<button onclick="resetCookie()">Reset Cookie</button>
<script>
function resetCookie()
{
    document.cookie = 0;
    writeValue();
}

function addOne()
{
    document.cookie++;
    writeValue();
}

function writeValue()
{
    document.getElementById('inc').value = document.cookie;
}

window.onload = function(){ 
    if(!document.cookie)
    {
        document.cookie = 0;
    }
    writeValue();
}
</script>
jvv
  • 188
  • 1
  • 14