goal4321
goal4321

Reputation: 121

Increment variable value of a variable on webpage refresh

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>

Upvotes: 1

Views: 3004

Answers (2)

HelpingHand
HelpingHand

Reputation: 1065

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

Upvotes: 3

blex
blex

Reputation: 25659

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.

Upvotes: -1

Related Questions