Javascript Onclick Increment Number

Javascript onclick increment a number as text

For one hand, if you want to increment the value you need to do x++ instead of x--. And after that, I think you will fix it with:

document.getElementById("num").innerHTML= x;

Because a div does not have a value property.

Increment number in a div on click

Do you mean like this?

const a = document.getElementById("a"),
div = document.getElementById("div");

a.addEventListener("click", event => {
//this is just to prevent redirects when you click the link
event.preventDefault();

//gets the number in div
const num = parseInt(div.innerHTML);

//increments the number
div.innerHTML = num + 1;
});
<a id="a" href="">Anchor Tag</a>
<div id="div">0</div>

How to increment a value using onClick in react

First of all you need to store the current like amount in the local state of the component. This way you can just display the current amount of likes and react will automatically update the display if you change the buttonLikes amount.

const [buttonLikes, setButtonLikes] = useState(comment_likes)

Then you'll need an event handler which will increment the like amount and post your changes to the DB


const handleClickLikeButton = (comment_id, user_id) => {
setButtonLikes((prevValue) => prevValue + 1)
LikeComment(comment_id, user_id)
}

Now your display logic will look like this

   <button className="btn" onClick={handleButtonLike(comment_id, user_id)}>
<div className="text">
<i className="fas fa-thumbs-up"></i>
<p>{buttonLikes}</p>
</div>
</button>

Javascript update/increment variable value on click

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

increase a number when click a button

You need to update the innerHTML upon updating the value in sum function.

let i = 1;

document.getElementById("par").innerHTML = i;

function sum() {
i++;
document.getElementById("par").innerHTML = i;
}
<p id="par">1</p>
<img onclick="sum()" height="40px" width="40px" src="sub.png">

Cant create button increment by one every click

There are multiple things wrong with your code.

  • You need to set id of the div to counter instead of its class. As you are retrieving the elements using its id in the javascript.
  • You are binding the click event of the button twice in your code. Once in HTML with onclick='adding()' and a second time in javascript with increment.addEventListener("click",adding), which causes it to increment twice on each click.