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

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

对于一个简单的表单,我有以下html代码

  1. <main>
  2. <form role="form">
  3. <fieldset id="personal-information" name="personal-information">
  4. <legend>Personal Information</legend>
  5. <section class="usernameSection" name="first-name">
  6. <label for="username">username:*</label>
  7. <input
  8. id="username"
  9. type="text"
  10. name="textfield"
  11. placeholder="username"
  12. />
  13. </section>
  14. <br />
  15. <section class="passwordSection" name="passwordSection">
  16. <label for="password">password:*</label>
  17. <input
  18. id="password"
  19. type="password"
  20. name="password"
  21. placeholder="password"
  22. />
  23. </section>
  24. <section class="submit" name="sumbit">
  25. <button id="submitButton" type='button' name="submit button"/>Sign in</button>
  26. </section>
  27. </fieldset>
  28. </form>
  29. </main>

在js中,我有以下代码:

  1. function signIn(userName, password) {
  2. console.log(userName,password)
  3. }
  4. const currentUsername = document.getElementById("username");
  5. const currentPassword = document.getElementById("password");
  6. const submitButton = document.getElementById("submitButton");
  7. submitButton.addEventListener("click", () => {
  8. signIn(currentUsername.innerText, currentPassword.innerText);
  9. });

这个想法只是记录用户在这个字段中输入的用户名和密码,但每当我这样做时,控制台就会打印出来 "" "" 我是否使用.innertext错误地获取了输入?
提前谢谢

9nvpjoqh

9nvpjoqh1#

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

  1. function signIn(userName, password) {
  2. console.log(userName,password)
  3. }
  4. const currentUsername = document.getElementById("username");
  5. const currentPassword = document.getElementById("password");
  6. const submitButton = document.getElementById("submitButton");
  7. submitButton.addEventListener("click", () => {
  8. signIn(currentUsername.value, currentPassword.value);
  9. });
  1. <main>
  2. <form role="form">
  3. <fieldset id="personal-information" name="personal-information">
  4. <legend>Personal Information</legend>
  5. <section class="usernameSection" name="first-name">
  6. <label for="username">username:*</label>
  7. <input
  8. id="username"
  9. type="text"
  10. name="textfield"
  11. placeholder="username"
  12. />
  13. </section>
  14. <br />
  15. <section class="passwordSection" name="passwordSection">
  16. <label for="password">password:*</label>
  17. <input
  18. id="password"
  19. type="password"
  20. name="password"
  21. placeholder="password"
  22. />
  23. </section>
  24. <section class="submit" name="sumbit">
  25. <button id="submitButton" type='button' name="submit button"/>Sign in</button>
  26. </section>
  27. </fieldset>
  28. </form>
  29. </main>
展开查看全部

相关问题