【问题标题】:why input value is an empty string in this form? [duplicate]为什么输入值是这种形式的空字符串? [复制]
【发布时间】:2021-12-02 09:20:45
【问题描述】:

我知道它应该很简单,但我仍然无法意识到问题所在。我已经创建了带有用于变量的 Id 的表单,然后在提交后我想查看输入的值,但我得到“”。

<form action="signIn.html" method="get">
<input type="text" name="name" id="names" placeholder="Name">
<input type="email" name="email" id="email" placeholder="Email">
<input type="password" name="password" id="password" placeholder="Password">
<label for="terms">
<input type="checkbox" name="terms" id="terms" value="terms">I agree to the Terms and Privacy Policy
</label>
  <div class="button">
  <input class="btn signUp" type="submit" value="Sign Up">                            
  </div>
const formulario = document.querySelector("form");
const nombre = document.querySelector("#names").value;
const email = document.querySelector("#email").value;
const password = document.querySelector("#password").value;
let correctData = [];
let errors = [];


formulario.addEventListener("submit", (e) => {
    e.preventDefault()
     console.log(nombre)
    console.log(email)
    console.log(password)
});

【问题讨论】:

    标签: javascript html input return-value


    【解决方案1】:

    您正在检索页面加载时输入的值(这是一个空白字符串,因为最初输入没有值)。

    相反,在submit 事件处理程序中获取value

    const formulario = document.querySelector("form");
    const nombre = document.querySelector("#names");
    const email = document.querySelector("#email");
    const password = document.querySelector("#password");
    let correctData = [];
    let errors = [];
    
    
    formulario.addEventListener("submit", (e) => {
      e.preventDefault()
      console.log(nombre.value)
      console.log(email.value)
      console.log(password.value)
    });
    <form action="signIn.html" method="get">
      <input type="text" name="name" id="names" placeholder="Name">
      <input type="email" name="email" id="email" placeholder="Email">
      <input type="password" name="password" id="password" placeholder="Password">
      <label for="terms">
    <input type="checkbox" name="terms" id="terms" value="terms">I agree to the Terms and Privacy Policy
    </label>
      <div class="button">
        <input class="btn signUp" type="submit" value="Sign Up">
      </div>

    【讨论】:

    • 太棒了!!!!谢谢你哦
    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 2016-08-03
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多