Reputation: 23
I'm pretty new to writing code and I am using JavaScript and HTML in Visual Studio Code. I've been trying to solve the following exercise which is to create a button that counts how many times it is being pushed.
The HTML part is done, but I'm stuck in the JavaScript part.
Any advice to solve such a thing?
let counter
document.querySelector("#btnPush").addEventListener("click", plus)
function plus() {
counter = 0;
document.querySelector("#pCounter").innerHTML = counter + 1
}
Upvotes: 1
Views: 105
Reputation: 26
let counter = 0
document.querySelector("#btnPush").addEventListener("click", plus)
function plus() {
counter++;
document.querySelector("#pCounter").innerHTML = counter
}
<button id="btnPush">button</button>
<p id="pCounter">0</p>
Upvotes: 1
Reputation: 382
This is very basic code for counter: you can utilized it ad per your demand...
let counter = 0;
document.querySelector("#btnadd").addEventListener("click", plus)
function plus() {
document.querySelector('#display').value = ++counter;
}
<p align="center">
<input type="text" id="display">
<br/>
<input type="button" id="btnadd" value="Click here">
</p>
Upvotes: 0
Reputation: 11120
It looks like you're changing the content/value of input type
element, which you should do by changing value
, not innerHTML
.
Check this out:
<html>
<p align="center">
<input type="text" id="pCounter" style = "padding:.5%; margin:10px"></input>
<br/>
<input type="button" id="btnPush" value="Click here"></input>
</p>
<script>
let counter = 0;
document.querySelector("#btnPush").addEventListener("click", plus)
function plus() {
document.querySelector('#pCounter').value = ++counter;
}
</script>
</html>
Upvotes: 0
Reputation: 71
So the problem with your code is that you define your counter inside your method. This means, that each time your method is startet, it sets the counter to zero. The soulution would be to write let counter = 0; outside of you method and then deleting the counter = 0; line inside the method
Upvotes: 0