0
how do i add value everytime i click a button?
js and html btw
4 odpowiedzi
+ 4
You could have a global JS variable. On each click, you add 1 by using a function that is attached to the button.
If you link your code, we can check on it.
+ 1
By onclick attribute
0
1. Assign a class, id or data-attribute to your button and the element which includes your counter. Something like this:
<p id="counterValue">Counter: 0</p>
<button id="counterButton">
2. Go to Javascript and store your html elements in variables:
let button = document.getElementById("counterButton");
let counterElement = document.getElementById("counterValue")
3. assign an initial value of your counter to a variable so we can increment that every time you click the button:
let counter = 0;
4. Now we need a Event Listener which listens to the button and triggers every time we click on the button:
button.addEventListener("click", () => {
counter++;
counterElement.innerHTML = "Counter: " + counter;
}
counter++ means that we add +1 everytime we click on the button.
counterElement.innerHTML replaces the content of your <p> with "Counter: " and the new Value.
Note: Don't use click events inside your html like: onclick="functionName".
It is bad practice in Software developing. Always seperate your stylesheet and script. In Software developing we call this "Separation of Concerns".
This helps to keep your code clean and clear