skip to Main Content

I am following this online free course on YouTube, this is the link if you want to visit it:
"Youtube link", but at around 2:15:00, he shows how to call javascript variables in HTML tags and log them onto the console. My problem is that It doesn’t show the variables value in the console log when I do the same as him.
for example, if I write Show amount and I have a variable in a script with a name value and a value of 0, it will show a space in the console when I click the button but for the guy, it shows the actual value (which is 0).

my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>javascript loggin</title>
  </head>
  <body>
    <button onclick="
      console.log(`Show Count: ${value}`)
    ">Show Count</button>
    <script>
      let value = 0;
    </script>
  </body>
</html>

Here is an image of the guys code: (If image isn’t loaded, his concept is pretty much the same as mine.)
For me when I click the button it shows the string placed within the console.log but fails to call and show the variable. the only way I can display the variable is by putting the console.log within the script otherwise it doesn’t work anywhere else in the html file.
what could be the reason? I would appreciate any help you could give regarding the matter.
(I am still a beginner so it will be appreciate even more if it is explained in simple language)

2

Answers


  1. You can´t use template literals (backtick) on HTML attributes. Any way, it´s not a best practice to put logic on HTML, just put a call to a function that will do the job:

    let value = 0;
    
    function btnClick() {
      // maybe you want to increment the value after each click
      value++;
      // print the result
      console.log(`Show Count: ${value}`);
    }
    <button onclick="btnClick()">Show Count</button>
    Login or Signup to reply.
  2. "value" is a pretty generic term that also has a meaning in HTML and JavaScript, so it’s best to not name variables that conflict with such names. If you change the variable name to something else, it will work.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>javascript loggin</title>
      </head>
      <body>
        <button onclick="
          console.log(`Show Count: ${count}`)
        ">Show Count</button>
        <script>
          let count = 0;
        </script>
      </body>
    </html>

    PS: While the use of let can cause issues, it’s not a problem here since the variable is being declared in the global scope.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search