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
As the name suggests,
getElementsByClassName
returns an array of elements, not a single element.If you want the first
loginInfo
instance, use:or
The
getElementsByClassName
function looks for all tags with the className ofloginInfo
.In your case two elements are found. So, use
to get the password.
Or have a look at what
document.querySelector
can do for you.