Javascript update/increment variable value on click

54,273

Solution 1

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++;
      }    

Solution 2

<input type="text" id="text" value="1"/>
function increase(){
    var textBox = document.getElementById("text");
    textBox.value++;
}
Share:
54,273
rohan_vg
Author by

rohan_vg

Updated on July 15, 2022

Comments

  • rohan_vg
    rohan_vg almost 2 years

    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?

  • John Dvorak
    John Dvorak over 11 years
    +1; note that polluting the global namespace is not recommended. You can avoid a global variable by using a self-invoking function.
  • John Dvorak
    John Dvorak over 11 years
    "you need a++" and "var a=1; should be declared before the function" don't seem very similar.
  • Martin
    Martin over 8 years
    how to maintain the incremented value in var a .
  • Miguel
    Miguel about 7 years
    does this add the increment at the end of the function??
  • Avnish alok
    Avnish alok almost 5 years
    shorter way.. liked that.. +1 for this
  • Ran Marciano
    Ran Marciano over 3 years
    Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes
  • Yunnosch
    Yunnosch almost 3 years
    I am unclear what you mean. Either "... but you should not. See this code how to avoid it." or "You have to put on ...". Maybe if you add either code or an explanation of what is wrong, why, how to solve it and how that works, then things might be clearer.