Home > Blockchain >  Why does it show 0 on click and not 1? (javascript html)
Why does it show 0 on click and not 1? (javascript html)

Time:01-17

I have built a small website, where I have a html button and an html input text field. I wanted to create a js function which manipulates the value of the input field by incrementing it by 1.

my html :

<button onclick="increment()">Click to   1!</button>
<input id="inc" type="text"/>

my javascript:

var i = 0;
function increment() {
var textbox = document.
getElementById("inc");
textbox.value = i;
i  ;

}

I wonder why the first time you press on the button it displays 0.

I defined i as 0. but in the function the last statement is : i ;

Therefore shouldnt it display 1 ? (0 1)

I am confused about how the function is executed line by line.

Hope you can help me understand it :)

CodePudding user response:

The issue is that you're setting textbox.value = i; before you increment i, and before the first time i is incremented, i is 0. To fix this, just move the statement that increments i before you set the value of the input. Like this:

const textbox = document.getElementById("inc");

let i = 0;
function increment() {
  i  ;
  textbox.value = i;
}

document.getElementById('inc_btn').addEventListener('click', increment);
<button id="inc_btn">Click to   1!</button>
<input id="inc" type="text" />

In the code above I also changed your onclick attribute into an event listener, which is the recommended practice in modern times. It is also better to make textbox a global variable, or else the browser will have to fetch it every time, rather than once.

  • Related