Html/javascript Button Click Counter
Solution 1:
Use var
instead of int
for your clicks
variable generation and onClick
instead of click
as your function name:
var clicks = 0;
functiononClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
<buttontype="button"onClick="onClick()">Click me</button><p>Clicks: <aid="clicks">0</a></p>
In JavaScript variables are declared with the var
keyword. There are no tags like int
, bool
, string
... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.
And the name 'click' is reserved by JavaScript for function names so you have to use something else.
Solution 2:
Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"
<html><head><title>Space Clicker</title></head><body><scripttype="text/javascript">var clicks = 0;
functionhello() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script><buttontype="button"onclick="hello()">Click me</button><p>Clicks: <aid="clicks">0</a></p></body></html>
Solution 3:
After looking at the code you're having typos, here is the updated code
var clicks = 0; // should be var not intfunctionclickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
}
Note: Don't use in-built handlers, as .click()
is javascript function try giving different name like clickME()
Solution 4:
<!DOCTYPE html><html><head><script>var clicks = 0;
functionmyFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
}
</script></head><body><p>Click the button to trigger a function.</p><buttononclick="myFunction()">Click me</button><pid="demo"></p></body></html>
This should work for you :) Yes var should be used
Solution 5:
Through this code, you can get click count on a button.
<!DOCTYPE html><html><head><metacharset="utf-8"><title>Button</title><linkrel="stylesheet"type="text/css"href="css/button.css"></head><body><scriptsrc="js/button.js"type="text/javascript"></script><buttonid="btn"class="btnst"onclick="myFunction()">0</button></body></html>
----------JAVASCRIPT----------
let count = 0;
function myFunction() {
count+=1;
document.getElementById("btn").innerHTML = count;
}
Post a Comment for "Html/javascript Button Click Counter"