[英]Getting data from the HTML form into JavaScript
我试图从表单输入中获取值,方法是单击“提交到JavaScript中的变量”。
但是我似乎不太幸运,因为控制台日志只是将变量显示为空。
的HTML
<html>
<head>
<meta charset="UTF-8">
<title>Registration</title>
</head>
<body>
<fieldset><legend>Registration</legend>
<form action="#" method="post" id="theForm">
<label for="username">Username<input type="text" name="username" id="username"></label>
<label for="name">Name<input type="text" name="name" id="name"></label>
<label for="email">Email<input type="email" name="email" id="email"></label>
<label for="password">Password<input type="password" name="password" id="password"></label>
<label for="age">Age<input type="number" name="age" id="age"></label>
<input type="hidden" name="unique" id="unique">
<input type="submit" value="Register!" id="submit">
</form>
</fieldset>
<div id="output"></div>
<script src="js/process.js"></script>
</body>
</html>
JS
var output = document.getElementById('output');
function addUser() {
'use strict';
var username = document.getElementById('username');
var name = document.getElementById('name');
var email = document.getElementById('email');
var password = document.getElementById('password');
var age = document.getElementById('age');
console.log(username.value);
console.log(name.value);
console.log(password.value);
}
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser();
} // End of init() function.
//On window load call init function
window.onload = init;
编辑是因为我需要在addUser上删除(),还需要在底部的addUser函数中添加return false。
在
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser();
}
这将把onsubmit
设置为undefined,因为addUser不返回任何内容。 要将函数addUser用作onsubmit函数,请改用此函数。
function init() {
'use strict';
document.getElementById('theForm').onsubmit = addUser;
}
您正在尝试传递函数本身而不是返回它。
另外,当我创建将要传递或设置的函数时,我发现像这样编写它们更合理:
var addUser = function(){
...
}
为了使您的功能正常工作,您可能需要这样做:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = function () { addUser(); }
}
您可以参考下面的帖子以获取更多说明:
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.