在js中的html输入字段中获取书面文本

oxf4rvwz  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(370)

对于一个简单的表单,我有以下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错误地获取了输入?
提前谢谢

9nvpjoqh

9nvpjoqh1#

你应该使用 .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>

相关问题