Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

403
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!