Javascript update / increment variable value on click

I have the 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> 

I am trying to do the following:

  • When a button is pressed, the value “a” will be displayed in the text box, and “a” will be increased.
  • When you press again, you now need to increase the value, but this does not happen.

Where am I going wrong?

+7
source share
8 answers

You only increase the local variable that goes away at the end of the function. You can do it:

  var a = 1; function increase(){ var textBox = document.getElementById("text"); textBox.value = a; a++; } 
+9
source
 <input type="text" id="text" value="1"/> 
 function increase(){ var textBox = document.getElementById("text"); textBox.value++; } 
+6
source

It is better to check the value of the text field. If it is empty a=1 else textfield.value++

0
source

i means var a=1; must be declared before function

0
source

you can use this. Just copy and paste

  <html> <head> <script type="text/javascript"> var a = 1; function increase(){ document.getElementById("text").value=a; a=a+1; } </script> </head> <body> <button type="button" onclick="increase()">show</button> <input type="text" id="text"> </body> </html> 
0
source

use this code

  var k = 1; function shashi() { document.getElementById('para').innerHTML = k; k++; } k = k; </script><br/> 

and calling the shashi () function on a click event

0
source

You should practice so as not to declare global variables until necessary. This sometimes leads to a hole in large applications. JS functions are also objects, which means they can have properties.

 <html> <head> <script> function increase(){ if( typeof this.counter == 'undefined' ) { this.counter = 1; } var textBox = document.getElementById("text"); textBox.value = this.counter; this.counter++; } </script> </head> <body> <button type="button" onclick="increase()">show</button> <input type="text" id="text"> </body> </html> 
0
source

You have a simpler approach that implements the increase and decrease buttons. A quick example using inline javascript:

 <!-- increment button --> <input type='button' name='add' onclick='javascript: document.getElementById("qty").value++;' value='+'/> <!-- quantity input --> <input name='qty' id='qty' style="text-align:center;" type="text" value="1" autocomplete="off" size="2"> <!-- decrement button --> <input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/> 
-1
source

All Articles