search

Home  >  Q&A  >  body text

Uncaught reference error: cnt is not defined

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粉696891871P粉696891871384 days ago484

reply all(2)I'll reply

  • P粉587780103

    P粉5877801032024-02-04 15:12:30

    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;
    }
    

    reply
    0
  • P粉635509719

    P粉6355097192024-02-04 11:33:27

    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!!!!!!
    

    reply
    0
  • Cancelreply