Home > other >  Uncaught ReferenceError: cnt is not defined
Uncaught ReferenceError: cnt is not defined

Time:12-27

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

CodePudding user response:

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"  onclick="dongjak_button();">CLICK</button>
<span>You Clicked This Button <span id="number"></span>Times!!!!!!</span>

CodePudding user response:

You have to use var or let to declare JavaScript variables.

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

"use strict";

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

Code still won't work though, 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;
}
  • Related