如何在JS中将输入值保存在变量中



我想把输入元素的值保存在一个变量中。但是它返回给我这个- [objecthtmlputelement]

这是我的HTML -

function userSubmit() {
let username = document.getElementById('userName');
let password = document.getElementById('passWord');

alert(username)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@500&display=swap" rel="stylesheet">

<link rel="stylesheet" href="style.css">
<title>B.O.M - Create Account</title>
</head>
<body>
<header>
<h1 class="heading">Welcome to Bank of Maharashtra.</h1>
</header>

<div class="container">
<h1 class="sub-heading">Create your account -</h1>

<div class="sub-container">
<label for="#userName">Username:</label>
<input type="text" name="" id="userName">
<br>
<label for="#passWord">Password:</label>
<input type="password" name="" id="passWord">
<br>
<input onclick="userSubmit()" type="submit" value="Confirm" id="confirm">
</div>

<img class="logo" src="bank_img3.webp" alt="" srcset="">
</div>

<script src="script.js"></script>
</body>
</html>

我没有得到我在输入字段中键入的用户名。请帮我解决这个问题。由于

这将记录input本身而不是它的值,您需要记录input.value

function userSubmit() {
let username = document.getElementById('userName');
let password = document.getElementById('passWord');
alert(username.value)
alert(password.value)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>B.O.M - Create Account</title>
</head>
<body>
<header>
<h1 class="heading">Welcome to Bank of Maharashtra.</h1>
</header>
<div class="container">
<h1 class="sub-heading">Create your account -</h1>
<div class="sub-container">
<label for="#userName">Username:</label>
<input type="text" name="" id="userName">
<br>
<label for="#passWord">Password:</label>
<input type="password" name="" id="passWord">
<br>
<input onclick="userSubmit()" type="submit" value="Confirm" id="confirm">
</div>
<img class="logo" src="bank_img3.webp" alt="" srcset="">
</div>
<script src="script.js"></script>
</body>
</html>

[object HTMLInputElement]只是您的username对象的字符串表示。{value: 'Users name'}

alert(JSON.stringify(username))

会让你知道你想看什么。

最新更新