从 HTML 表单中获取文本并传递给 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16745368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting text from HTML form and pass to JavaScript function
提问by d m
I am learning HTML/JavaScript and am writing a simple site to test what I've learned so far. I am trying to get the firstname and lastname entered by the user from an input form and then pass these names to a JavaScript function but for some reason, all I see in my popup window is:
我正在学习 HTML/JavaScript 并且正在编写一个简单的站点来测试我到目前为止所学到的知识。我试图从输入表单中获取用户输入的名字和姓氏,然后将这些名称传递给 JavaScript 函数,但由于某种原因,我在弹出窗口中看到的只是:
Hello [object HTMLInputElement]
你好 [对象 HTMLInputElement]
This is my html code:
这是我的 html 代码:
<!DOCTYPE html>
<html>
<head>
<title>Daynesh's Test Site</title>
<script>
function addUser(first, last)
{
alert("Hello " + first);
}
</script>
</head>
<body>
<h1>Registered Users</h1>
<p>Enter user name:</p>
<form>First name: <input type="text" name="firstname">
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit" onclick="addUser(firstname,'right')">
</form>
<hr>
<h3>Output</h3>
</body>
</html>
Can someone please explain what I'm doing wrong? I'm sure its something very simple that I'm not understanding here.
有人可以解释一下我做错了什么吗?我确定它的一些非常简单的东西我在这里不理解。
Thanks in advance!
提前致谢!
回答by Bahaa Odeh
in your code
在你的代码中
onclick="addUser(firstname,'right')"
firstname is nothing you don't define it before so you should define it in javascript or get value from input directly this your code after fix
名字不是你之前没有定义过的,所以你应该在 javascript 中定义它或者直接从输入中获取值修复后的代码
<!DOCTYPE html>
<html>
<head>
<title>Daynesh's Test Site</title>
<script>
function addUser(first, last)
{
alert("Hello " + first);
}
</script>
</head>
<body>
<h1>Registered Users</h1>
<p>Enter user name:</p>
<form>First name: <input type="text" name="firstname" id="firstname">
Last name: <input type="text" name="lastname">
<input type="submit" value="Submit" onclick="addUser(document.getElementById('firstname').value,'right')">
</form>
<hr>
<h3>Output</h3>
</body>
</html>
i hope my answer help you
我希望我的回答对你有帮助
回答by Dan Anderson
document.getElementByName('firstname').value
See a more detailed answer at: JavaScript: how to get value of text input field?
请参阅更详细的答案:JavaScript:如何获取文本输入字段的值?