[英]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.