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">
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">
Share
Improve this question
asked Jul 23, 2021 at 7:51
SepehrSepehr
856 bronze badges
2
- Does this answer your question? javascript onclick increment number – DeveloperLV Commented Jul 23, 2021 at 7:57
- I think a few more details of your code would help to answer this, like where is your function sub() that you refer to in onclick. Maybe this is the mistake and it is supposed to be sum()? – bluejambo Commented Jul 23, 2021 at 7:57
5 Answers
Reset to default 5
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>
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">
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">
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./metro/452/plus.png">