Search code examples
javascriptincrement

Javascript update/increment variable value on click


I have this following code: JS Fiddle

<html>
    <head>
        <script>            
            function increase(){
                var a = 1;
                var textBox = document.getElementById("text");
                textBox.value = a;
                a++;
            }            
        </script>
    </head>

    <body>
        <button type="button" onclick="increase()">show</button>
        <input type="text" id="text">
    </body>
</html>​

What I am trying to do is:

  1. On clicking the button the value of 'a' will be displayed in the textbox and 'a' will be incremented.
  2. On clicking again now the incremented value should be displayed but this doesn't happen.

Where am I going wrong?


Solution

  • You're only incrementing a local variable that goes away at end of function. You may do this :

          var a = 1;
          function increase(){
                var textBox = document.getElementById("text");
                textBox.value = a;
                a++;
          }