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++;
}
Author by
rohan_vg
Updated on July 15, 2022Comments
-
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:
- On clicking the button the value of 'a' will be displayed in the textbox and 'a' will be incremented.
- On clicking again now the incremented value should be displayed but this doesn't happen.
Where am I going wrong?
-
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 over 11 years"you need
a++
" and "var a=1;
should be declared before the function" don't seem very similar. -
Martin over 8 yearshow to maintain the incremented value in var a .
-
Miguel about 7 yearsdoes this add the increment at the end of the function??
-
Avnish alok almost 5 yearsshorter way.. liked that.. +1 for this
-
Ran Marciano over 3 yearsPlease 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 almost 3 yearsI 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.