【发布时间】:2021-04-22 15:53:25
【问题描述】:
所以我正在尝试创建一个基本函数,将我的用户名变量设置为小写,但我一直收到 TypeError
错误消息:index.js:12 Uncaught TypeError: Cannot read property 'value' of undefined 在 HTMLFormElement.onSubmit (index.js:12)
如果有人能在这里发现我做错了什么,我将不胜感激。
const logform = document.querySelector('#logform');
var username = document.querySelector('#usernameinput');
const password = document.querySelector('#passwordinput');
logform.addEventListener('submit', onSubmit);
function onSubmit(e) { //takes in event parameter
e.preventDefault();
var username = username.value.toLowerCase();
console.log(username.value);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login Portal</title>
<link rel="stylesheet" type="text/css" href="CSS/index.css">
</head>
<body>
<div class="loglogo">
<!-- logo container -->
<a href="https://www.waspc.org/" target="_blank">
<img src="IMAGE/logo.png" alt="IMAGE">
</a>
</div>
<form id="logform">
<div class="logscreen">
<!-- login container -->
<label><strong>Username</strong></label>
<!-- Username field -->
<input autocomplete="off" id="usernameinput" type="text" name="" placeholder="Enter Username" required>
<label><strong>Password</strong></label>
<!-- Password field -->
<input id="passwordinput" type="password" name="" placeholder="Enter Password" required>
<button type="submit"><a href="home.html">Login</a></button>
<!-- Login button -->
<button class="newbutton" type="button"><a href="newuser.html">New User</a></button>
<!-- New User button -->
<button type="reset">Cancel</button>
<!-- Cancel button -->
</div>
</form>
<script src="JS/index.js"></script>
</body>
</html>
【问题讨论】:
-
您需要提供更多信息,例如html代码和日志输出
-
id="usernameinput" 的元素是否是表单域,在变量赋值时是否存在?
-
尝试 console.log(username)... 你已经将用户名设置为字符串类型或其他东西,但不是对象
-
从
<button type="submit"><a href="home.html">Login</a></button>中删除链接并将var从用户名重命名为用户 -
你正在关注
username。username.value.toLowerCase()中的username指的是您在同一行声明的username,而不是您在顶部声明的那个。 (当然在某个地方有一些欺骗。)
标签: javascript html function frontend typeerror