I want to click button and count number but it’s not work.
and error message: Uncaught ReferenceError: cnt is not defined
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make777</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<button type="button" class="btn-click" onclick="dongjak_button();">CLICK</button>
<span>You Clicked This Button <span id="number"></span>Times!!!!!!</span>
<script src="./script.js"></script>
</body>
</html>
"use strict";
function dongjak_button(){
cnt = 0;
cnt++;
document.getElementById("number").value = cnt;
}
Help. I hope cnt variable works. and show on html
>Solution :
You’re in strict mode, and you didn’t declare your cnt variable. See MDN’s docs.
You also can’t change value on a span — you’ll need textContent instead. And, your cnt will reset every time, so you’ll want to store the variable outside of your function. All in all:
// stored outside the function so it increments rather than resets
let cnt = 0;
function dongjak_button(){
cnt++;
// use textContent, not value; also add a space
document.getElementById("number").textContent = cnt + ' ';
}
<button type="button" class="btn-click" onclick="dongjak_button();">CLICK</button>
<span>You Clicked This Button <span id="number"></span>Times!!!!!!</span>