Input receives no value when clicking the Button

Asked

Viewed 70 times

0

I’m having trouble using the getElementById.

When I run my code and click on the button, apparently the value entered in the input is not received.

Can someone help me?

var teste1 = document.getElementById("teste").value;

var button = document.querySelector("button");

button.onclick = document.write(teste1);
<input id="teste"/>
<button>Testar</button>

  • The onclick should call a function.

  • What do you mean the value is not received? Who should receive this value? Your problem is the getElementById?

2 answers

4

Your problem is that you need to read the value of the field by clicking the button and not before, see the example below:

var button = document.querySelector("button");

button.onclick = function(e){
   // deve ler o valor ao clicar e nao antes
    var teste1 = document.getElementById("teste").value;
    document.write(teste1);
}
<input id="teste"/>
<button>Testar</button>

  • A question: I have to assign the entire function to the button.onclick or can I write the function and then do button.onclick = Function();? or else Document.write("The test value is: "+Function());

  • You can. If your Function no parameters, it can be very simple: button.onclick = nomedasuafunction

  • You can do it this way too: button.onclick = function(e){ nomedasuafunction(e); }

  • Man, thank you so much for your help!

1

Here’s an example using the button click event:

HTML:

<input id="teste"/>
<button>Testar</button>
<span id="result"></span>

JS:

var teste1 = document.getElementById("teste");
var result = document.getElementById("result");

var button = document.querySelector("button");

button.addEventListener('click', function() { 
  result.innerText = teste1.value;
//   document.write(teste1.value);
})

Browser other questions tagged

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