繁体   English   中英

如何阻止 HTML 表单在 JavaScript 中返回未定义的值?

[英]How to stop HTML form from returning undefined value in JavaScript?

我想检索 HTML 表单的输入值,但该变量仅在函数之外返回未定义。

这是我的 HTML:

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

这是随之而来的 JS:

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

console.log(username)语句在函数内时,它返回输入; 但是,当console.log(username)语句在函数之外时,它会返回 undefined。

任何帮助表示赞赏!

您需要在函数中调用 console.log 。

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM