Home > Software design >  How to stop HTML form from returning undefined value in JavaScript?
How to stop HTML form from returning undefined value in JavaScript?

Time:06-06

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!

CodePudding user response:

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>

  • Related