Reputation:
Here is my code:
<html>
<body>
<script>
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
</script>
<p>Clicks: <a id="clicks">0</a></p>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
<button type="button" onClick="clickME()">Click me</button>
</body>
</html>
I'm trying to use this example I found:
<body>
<h1>Single click JS Button</h1>
<button type="submit" onClick="this.disabled = true; return true;">Submit</button>
</body>
I'm confused on how to use the onClick="this.disabled = true;
part because for my code I already have the function called when I wrote onClick. I used onClick="clickMe()
.
Are you allowed to have onClick
twice? I want to use the onClick="this.disabled = true;
because I don't want to keep increasing the amount of clicks if the user clicks the button again. If they click it once I only want to increment once and then disable the button or just not increase the count after.
I do not think this is a duplicate of the other question, as that is jQuery click() only once, but I'm using JavaScript. I have not learned jQuery (jQuery click() only once)*
Upvotes: 4
Views: 1260
Reputation: 4346
addEventListener
option once:true
- looks like a perfect option in your case.
More explanations in the code
var clicks = 0
function clickME(event) {
clicks += 1
document.getElementById("clicks").innerText = clicks // innerText is more suitable in this case
if (event.target.className.includes(`auto-disable`)) {
event.target.disabled = true // auto disabling if you need it
}
}
document.querySelectorAll(`button`) // select all buttons
.forEach( // loop through the elements
// addEventListener with options once:true. once option designed exactly for your purposes, to fire event only once
el => el.addEventListener(`click`, clickME, {once: true})
)
<p>Clicks: <a id="clicks">0</a></p>
<button type="button">Click me</button>
<button type="button">Click me</button>
<button type="button" class="auto-disable">Click me</button>
<button type="button" class="auto-disable">Click me</button>
Upvotes: 1
Reputation: 5895
Please take a look here:
var clicks = 0;
function clickME(el) {
el.disabled = true;
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
<p>Clicks: <a id="clicks">0</a></p>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
<button type="button" onClick="clickME(this)">Click me</button>
Upvotes: 3