gpt4 book ai didi

javascript - 将数据从 HTML 表单获取到 JavaScript

转载 作者:行者123 更新时间:2023-11-28 19:33:18 25 4
gpt4 key购买 nike

一旦您单击提交到 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(){
...
}

关于javascript - 将数据从 HTML 表单获取到 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26342710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com