我一直在尝试做一个简单的登录系统(本地),我有点困惑…我如何接受用户写到文本字段中的输入,在控制台中打印它,并将它存储在变量中?
我的HTML代码:
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form name="">
<label for="text1">Username:</label>
<input type="text" name="text1">
<label for="text2">Password:</label>
<input type="text" name="text2">
<button onclick="password(), username()">login</button>
</form>
</body>
</html>
对于我的JS,我想让''password()和username()'函数在不同的文件中分别检查这两个函数。
JS密码文件:
const Psword = 'Password9' //just an example
function password() {
console.log(Psword)
// if (user input from password field) = Psword
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
JS用户名文件:
var Username = 'Subject09'
function username() {
console.log(Username)
// if (user input from username field) = Username
// alert('Login sucessfull redirecting!)
// else{
// alert('Username or password are incorrect')
// }
}
编辑:添加了我的JS代码。(注意:我把代码拆分成了两个不同的JS文件,因为我只想让它在结果中变得简单。)
为您的输入和按钮设置ID。您可以通过将type=button“添加到您的按钮来阻止提交。
只需在您的按钮上设置一个onclick事件,并获取您的输入值。
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<label for="text1">Username:</label>
<input type="text" name="text1" id="username">
<label for="text2">Password:</label>
<input type="text" name="text2" id="password">
<button type="button" id="submitBtn">login</button>
</form>
window.onload = function() {
document.getElementById('submitBtn').addEventListener('click', onSubmit);
}
function onSubmit() {
console.log(document.getElementById('username').value);
console.log(document.getElementById('password').value);
// Do what you want with data
// You can submit with .submit()
document.forms['form'].submit();
}
这样,当用户键入某些内容时,我们将每个字符保存在一个变量中。
您也可以使用
更新:我正在向您展示表单提交方法。
null
const form = document.querySelector("form");
form.addEventListener("submit",(e)=>{
e.preventDefault();
if(form["text1"].value && form["text2"].value){
console.log("Submitted the form");
form.reset();
}else{
console.log("Provide required values");
}
})
<!DOCTYPE html>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="username.js"></script>
<script src="password.js"></script>
</head>
<body>
<title>Login #1</title>
<h2>Simple login system</h2>
<form>
<div>
<label>Username:</label>
<input type="text" name="text1" >
</div>
<div>
<label>Password:</label>
<input type="text" name="text2">
<div>
<button type="submit">login</button>
</form>
</body>
</html>