skip to Main Content

My project has a sign up form that collects user’s data. I connected the JavaScript and tried to make it so that when the user hits the sign up button, the JavaScript file saves it as a variable named input. Here is my code for HTML:

   <input type="text" class="loginInfo" placeholder="Enter Email" name="email" required>
              
   <label for="psw"><b>Password</b></label>
   <input type="password" class="loginInfo" placeholder="Enter Password" name="psw" required>
              
    <label for="psw-repeat"><b>Repeat Password</b></label>
    <input type="password" class="loginInfo" placeholder="Repeat Password" name="psw-repeat" required>
    <div class="clearfix">
    <button type="submit" class="signupbtn" onclick="othername();">Sign Up</button>

And here is my JavaScript:

function othername() {
    var input = document.getElementsByClassName("loginInfo").value;
    alert(input);
}

I tried to make it so that the variable was defined in the HTML but it didn’t work. The problem is that whenever the user hits the sign up button, the browser gives an undefined message.

2

Answers


  1. As the name suggests, getElementsByClassName returns an array of elements, not a single element.

    If you want the first loginInfo instance, use:

    document.getElementsByClassName("loginInfo")[0].value;
    

    or

    document.querySelector(".loginInfo").value;
    
    Login or Signup to reply.
  2. The getElementsByClassName function looks for all tags with the className of loginInfo.

    In your case two elements are found. So, use

    var input = document.getElementsByClassName("loginInfo")[1].value;
    

    to get the password.

    Or have a look at what document.querySelector can do for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search