1

I have code which just increments a value by 10 on every button click. I want that code to increment the value whenever I refresh the page. How do I do that?

Here is the code:

<html>
<head>
<script type="text/javascript">
function reveal() {
var val = document.getElementById("outputtext").value;
var result = parseInt(val) + parseInt(10);
document.getElementById("outputtext").value = result;
}
</script>
</head>

<body>
<p> <h3>Click on below button to increase the value by 10<h3> </p>

<button onclick="reveal()"> Increment</button>

<table>
<tr>
<td><textarea id="outputtext">10</textarea></td>
</tr></table>
</body>
</html>
goal4321
  • 121
  • 3
  • 17

2 Answers2

3

For the title of your question, you might use the following Javascript function to bring up the previous page:

history.back();

as stated in this question on SO: How to emulate browser back button using javascript


If you want to increment a variable on page refresh with Javascript, you should save this variable as a cookie on the users browser:

document.cookie="increment=10";

Either of these links might help you with this: http://www.w3schools.com/js/js_cookies.asp http://www.htmlgoodies.com/beyond/javascript/article.php/3470821

Community
  • 1
  • 1
HelpingHand
  • 1,045
  • 11
  • 26
-1

You could do this without cookies, by using a hash (#value) in the URL. Try this code :

<html>
<head>
</head>

<body>
    <h3>Click on below button to increase the value by 10<h3>

    <button onclick="reveal()"> Increment</button>

    <table>
        <tr><td><textarea id="outputtext">10</textarea></td></tr>
    </table>

    <script type="text/javascript">

    //Get the last value
    var current = parseInt(location.hash.slice(1));
    //If it is set, increment it
    if(current){
        document.getElementById("outputtext").value = current + 10;
        location.hash = '#' + (current+10);
    }

    function reveal() {
        var val = document.getElementById("outputtext").value;
        var result = parseInt(val) + parseInt(10);
        document.getElementById("outputtext").value = result;
        //Set the value
        location.hash = '#' + result;
    }

    </script>
</body>
</html>

Note that I moved the javascript to the end of the file, so that #outputtext is already defined when the code gets executed.

blex
  • 24,941
  • 5
  • 39
  • 72
  • 1
    Yes, that would work too. I stay away from hash values though, because they can be a cause for [Spaghetti code](http://en.wikipedia.org/wiki/Spaghetti_code) and confusion. – HelpingHand Jun 05 '14 at 16:02
  • @HelpingHand That is true, on a big project I would recommend using cookies, this is just an alternative way to do it. – blex Jun 05 '14 at 16:08