Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

400
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda