Uncaught reference error: cnt is not defined
P粉696891871
P粉696891871 2024-02-03 21:58:31
0
2
474

I want to click the button and count the quantity but it doesn't 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 want the cnt variable to be valid. and displayed on html

P粉696891871
P粉696891871

reply all(2)
P粉587780103

You must use var or let to declare JavaScript variables.

Learn more here: https://www.w3schools.com/js/js_variables.asp

"use strict";

function dongjak_button(){
    let cnt = 0;
    cnt++;
    document.getElementById("number").textContent = cnt;
}

The code still doesn't work because you need to get the count from #number first.

"use strict";

function dongjak_button(){
    const number = document.getElementById("number");
    const value = number.textContent;
    
    let cnt = value ? Number(value) : 0;
    cnt++;
    number.textContent = cnt;
}
P粉635509719

You are in strict mode and have not declared a cnt variable. See MDN Documentation.

You also cannot change the value on span — you need textContent. Also, your cnt is reset every time, so you need to store the variable outside the 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 + ' ';
}

You Clicked This Button Times!!!!!!
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template