Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to increase the value written on the button starting from 0 and increment till the user stop clicking the button.
For Example: If User clicked the button one time, the value should increase from 0 to 1 and then if clicked again, then the value should be 1 to 2.

What I have tried:

Here is my HTML:
<div class="button">
  <button type="button" class="btn">0</button>
</div>


And my Javascript File:
var buttonTarget = document.getElementsByClassName("btn");
var counter = 0;

function incrementer(){
  buttonTarget.innerHTML = counter.toString();
  counter++;
  return counter;
}


What I am doing wrong? Any help would be appreciated :)
Posted
Updated 15-Jan-19 18:05pm
v2
Comments
GKP1992 15-Jan-19 22:44pm    
Try calling the incrementer function on the button click.

1 solution

Here are my comments.

1. As suggested by other member, you need to update the code to hook up the button click event.

2. getElementsByClassName return array of object, assuming you want the code to access the first button, then the code should look like document.getElementsByClassName("btn")[0];

3. The button initial text value is 0 on page load, so on button click, the counter should show 1, either move the counter++; to the top or start the counter from 1

4. You can also update the button to include an id attribute i and the JavaScript to use getElementById method

HTML
<div class="button">
  <button type="button" class="btn" id="btn" onclick="incrementer()">0</button>
</div>


JavaScript
var buttonTarget = document.getElementsByClassName("btn")[0];
var counter = 1;

function incrementer(){
//document.getElementById("btn").innerHTML = counter.toString();
  buttonTarget.innerHTML  = counter.toString();
  counter++;
  return counter;
}



Document.getElementsByClassName() | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900