increase a number when click a button

Viewed 568

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">

5 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>

First of all, you'll have to get the number that is currently displayed in your p tag. You can either read it from the dom every time or just keep track of it in javascript. We should also get a reference to your p tag for later use.

let i = 1;
let p = document.getElementById("par");

Next, when you are calling your sub function, you are incrementing i, but you are not applying the changed value to your p tag. You can do it like so:

function sum() {
  i++;
  p.innerHTML = i;
}

Your html can stay the way it is.

You can defined a global variable to store the value, also you need make the function name keep the same

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

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">

function sum() {

    var p = document.getElementById("par") ;

    p.innerHTML = parseInt(p.innerHTML) + 1 ;

}
<p id="par">1</p>

<img onclick="sum()" height="40px" width="40px" src="https://img.icons8.com/metro/452/plus.png">

Related