Function does not recognize global variable in Javascript

Asked

Viewed 410 times

-1

When I use variables to store content from text boxes, to can execute in a function (just like it is in the code I left here), if the variables are not inside the function, the code does not work correctly. The code below was made to capture the contents of a number text box and send an Alert with what was inside the box, but only works if I put the variables inside the function. I wanted to understand why since the variable is in the global scope.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="number" id="num">

    <input type="button" value="Ok" onclick="clicar()">
    <script>
        var num = document.getElementById('num')
        var numero = Number(num.value)

        function clicar(){
            window.alert(numero)
        }
    </script>
</body>
</html>

  • That’s weird, I took a test here and it was no problem. If your Javascript code is exactly the one you put in the question, is that you have not forgotten to call the function no ?

  • I think you should try [Edit] your question to add code as text. As can be read here, posting an image as code is not good practice on this site, and your question may be negatively so.

1 answer

0


Well, there are some reasons for this, as we will see below.

A code is rendered/interpreted from top to bottom by the browser, so if you make, for example, a code like this:

<html>
  <head>
    <script src="main.js"></script>
  </head>
  <body>
    <input type="text" onclick="clica()" id="texto"/>
  <body/>
</html>

And in the main.js file, be:

var texto = document.getElementById('texto')
function clica(){  
   alert(texto)
}

It will not work as expected because when the interpreter goes through the first line of Javascript code, var texto = document.getElementById('texto'), the HTML element (input) has not yet been rendered, as its HTML code is below the Javascript code, so the global variable receives Undefined, since, at that point in the code, as I said, the HTML element was not rendered, i.e., DOESN’T YET EXIST. The function recognizes the global variable normally, but its content is Undefined.

To circumvent this problem, the most common is to involve the assignment made to the global variable with the function callback call on time click the button. Thus, each time the element is clicked (and the function, consequently, is called), the assignment will be made.

There is yet another way: put the Javascript code, or the href from it, below, after all the HTML code. Thus, Javascript code will only be interpreted when all HTML elements have been rendered by the browser rendering engine. However, the problem with this "approach" is that the value will not be updated every click, since the JS code outside of any function is only interpreted once.

An example of this way of doing is given below.

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <input type="text" name="texto" id="texto">
    <button onclick="clicar()">clique em mim!</button>
    <script>
        var texto = window.document.getElementById('texto').value
        function clicar(){
            window.alert(texto)
        }
    </script>
</body>
</html>

  • 1

    You emphasized "there is no" well, huh.

  • Sorry I didn’t put all the code. I tried to edit the post a few times to try to put the whole code, but it was only going to be a piece. Now that I’ve used a photo.

  • All right. I added another code to make understanding easier, you can understand with this explanation?

  • I understood your script, but when I run, if your variable "text" is not within the "click" function, it only leaves empty Alert. I tested with the variable within the function and it worked.

  • Precisely, and I explain why this happened in my reply.

  • The answer is confusing. The problem is not that it picks up a reference to the input at the moment it is picking up, it works with the question code. The problem is taking the value of the element only once, instead of every click.

  • But I explain both cases: when it only picks up once and when it doesn’t pick up (in case the HTML element hasn’t been created yet)!!!!!

  • The top half of the answer talks about using external js, which is not the case with the question. The bottom half includes an example with the same question code problem! Even you explaining the question of value, in my opinion remains confused...

  • Well, unfortunately if you can’t interpret well, I can’t do anything but advise you to read more - and various things.

  • I was trying to make a constructive criticism. But if you prefer to dispense with the criticism offending me, patience.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.