can’t get value from javascript input

Asked

Viewed 303 times

-2

I’m not getting value from input

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Index</title>
</head>

<body>
  <input type="text" id="numero">olaa</input>
  <button onclick="enviar()">mostrar</button>
  <p id="par"></p>


  <script>
    var par = "";

    var numero = document.getElementById('numero').value;

    function enviar() {
      par = document.getElementById('par').innerHTML = numero.value;
    }
  </script>

</body>

</html>

1 answer

2

You can take the value of input through the document.getElementById('numero').value. As you can see, the id must be the input, that part you did right, missed just put inside the function enviar. Already the .innerHTML, no. It serves to change the content of the page. To do this, do the following: document.getElementById('par').innerHTML = "conteúdo para aparecer".

And also you put "olaa" in the input, it does not work that way, so I removed in the following code.

Your code would look like this:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Index</title>
</head>

<body>
  <input type="text" id="numero"></input>
  <button onclick="enviar()">mostrar</button>
  <p id="par"></p>

<script>
   function enviar() {
      var numero = document.getElementById('numero').value;
      document.getElementById('par').innerHTML = numero;
   }
</script>

</body>

</html>

  • thanks for the answer, but my biggest problem was the following: I put the input after captured in a variable and then I put it for when the button was clicked it alerts the variable but always gave: NAN or Undefined or 0 or nothing

  • Yes, this happened before because the "number" variable assignment is outside the send function. That is, you didn’t "capture" the input value.

Browser other questions tagged

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