Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increase a number when click a button

I want to write Javascript code which can increase a number when we click a button.Can you help me? I tried this but it doesn't work.

var document.getElementById("par").innerHTML = i;
        function sum(){
            i++;
        }
<p id="par">1</p>
<img onclick="sub()" height="40px" width="40px" src="sub.png">
like image 569
Sepehr Avatar asked Mar 18 '26 20:03

Sepehr


2 Answers

const button = document.querySelector("#increaser");
const res = document.querySelector("#result");

button.addEventListener("click", () => {
  res.textContent++
});
<div>
    <p id="result">1</p>
    <button id="increaser">Add</button>
</div>
like image 186
B.Ch. Avatar answered Mar 20 '26 09:03

B.Ch.


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">
like image 43
TechySharnav Avatar answered Mar 20 '26 08:03

TechySharnav