I'm working on a password matching validator and am stuck. It seems like the code is structured correctly but it reads the passwords as matching no matter what. Also would like to know what I'm doing wrong in regards to getting the event to keep validating without reloading the page, I was hoping event
would get the job done.
Here is the Javascript
<script>
const pass1 = document.getElementById("password1");
const pass2 = document.getElementById("password2");
const p = document.getElementById("confirm")
function passCheck () {
if (pass1 !== pass2) {
return p.innerHTML= "Passwords do not match";
}
else {
return p.innerHTML="Passwords match";
}
}
pass2.addEventListener("keyup", function() {
event ;
passCheck(pass1, pass2);})
</script>
Here is the HTML
<body>
<div >
<div >
<form action="#" method="post">
<div >
<label for="FName">First name</label>
<input type="text" id="FName" name="FName" placeholder="Your First Name" required>
</div>
<div >
<label for="LName">Last Name</label>
<input type="text" id="LName" name="LName" placeholder="Your Last Name" required>
</div>
<div >
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Your Email" required>
</div>
<div >
<label for="phone">Phone Number</label>
<input type="number" id="phone" name="phone" placeholder="Your Phone Number" required>
</div>
<div >
<label for="password1">Password</label>
<input type="text" id="password1" name="password1" required>
</div>
<div >
<label for="password2">Confirm Password</label>
<input type="text" id="password2" name="password2" required>
<p id="confirm"></p>
</div>
<button type="submit" >Create Account</button><br>
</form>
</div>
<p>Already have an account? <a>Log in</a></p>
</div>
</div>
</body>
CodePudding user response:
You're getting the elements:
const pass1 = document.getElementById("password1");
What you want are the values:
const pass1 = document.getElementById("password1").value;
Alternatively, if you need to reference the elements otherwise (such as when calling pass2.addEventListener
), you can reference the values just during the comparison:
if (pass1.value !== pass2.value) {
However you want to structure the code is up to you. The main point to remember is when you're referencing the entire HTML element and when you just want the .value
from that element (specifically for <input>
elements).
As an aside, you're pass arguments to a function that doesn't expect any:
passCheck(pass1, pass2);
Either add the parameters to the function itself, or continue using the globally scoped variables within the function and don't pass anything to it:
passCheck();