gpt4 book ai didi

javascript - 在 JS 的 HTML 输入字段中获取书面文本

转载 作者:行者123 更新时间:2023-12-04 07:23:53 24 4
gpt4 key购买 nike

我在 html 中有以下代码用于简单的表单

<main>
<form role="form">
<fieldset id="personal-information" name="personal-information">
<legend>Personal Information</legend>

<section class="usernameSection" name="first-name">
<label for="username">username:*</label>
<input
id="username"
type="text"
name="textfield"
placeholder="username"
/>
</section>
<br />
<section class="passwordSection" name="passwordSection">
<label for="password">password:*</label>
<input
id="password"
type="password"
name="password"
placeholder="password"
/>
</section>
<section class="submit" name="sumbit">
<button id="submitButton" type='button' name="submit button"/>Sign in</button>
</section>
</fieldset>
</form>
</main>
在 js 中,我有以下代码:
function signIn(userName, password) {
console.log(userName,password)
}

const currentUsername = document.getElementById("username");
const currentPassword = document.getElementById("password");
const submitButton = document.getElementById("submitButton");

submitButton.addEventListener("click", () => {
signIn(currentUsername.innerText, currentPassword.innerText);
});
这个想法只是记录用户在此字段中输入的用户名和密码,但是每当我这样做时,控制台都会打印 "" ""我是否通过使用 .innerText 错误地获取了输入?
提前致谢

最佳答案

您应该使用 .value而不是 .innerText .

function signIn(userName, password) {
console.log(userName,password)
}

const currentUsername = document.getElementById("username");
const currentPassword = document.getElementById("password");
const submitButton = document.getElementById("submitButton");

submitButton.addEventListener("click", () => {
signIn(currentUsername.value, currentPassword.value);
});
<main>
<form role="form">
<fieldset id="personal-information" name="personal-information">
<legend>Personal Information</legend>

<section class="usernameSection" name="first-name">
<label for="username">username:*</label>
<input
id="username"
type="text"
name="textfield"
placeholder="username"
/>
</section>
<br />
<section class="passwordSection" name="passwordSection">
<label for="password">password:*</label>
<input
id="password"
type="password"
name="password"
placeholder="password"
/>
</section>
<section class="submit" name="sumbit">
<button id="submitButton" type='button' name="submit button"/>Sign in</button>
</section>
</fieldset>
</form>
</main>

关于javascript - 在 JS 的 HTML 输入字段中获取书面文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68322613/

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