Search code examples
javascripthtmlinputreturn-value

why input value is an empty string in this form?


I know it should be simple but i still can't realize what is the problem. I've created the form with the Id that i use for the variables and then after the submit i want to see the value of the input but i get "".

<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)
});

Solution

  • You are retrieving the values of the inputs on page load (which is a blank string, because initially the input has no value).

    Instead, get the value inside the submit event handler.

    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>