Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

401
Visualizações
How to stop HTML form from returning undefined value in JavaScript?

I want to retrieve the input value of an HTML form, but the variable only returns undefined when outside of a function.

Here is my HTML:

<form name="form">
        Enter name: 
   <input type="text" id="answer">
   <input type="button" value="Submit" onclick="answerInput()">
</form>

And here is the JS that goes with it:

function answerInput() {
    username = document.getElementById("answer").value
}
console.log(username)

When the console.log(username) statement is within the function, it returns the input; however, when the console.log(username) statement is outside the function, it returns undefined.

Any help is appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to call console.log inside your function.

function answerInput() {
    username = document.getElementById("answer").value;
    console.log(username)
}
<form name="form">
        Enter name: 
   <input type="text" id="answer">
   <input type="button" value="Submit" onclick="answerInput()">
</form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda