I am currently making a javascript and html mini-login box. I have created a javascript code which checks the length of the password and checks if confirm password and password are the same. Here is the code...
<form name = "logme">
<fieldset>
<legend>Create Your Account!</legend>
<br>
<p>Username:*<input type="text" name="user" placeholder="Enter Your Name">
<br>
<br>
Password:*<input type="password" id="pass">
<br>
<p>Confirm Password:*<input type="password" id="passwd">
<br>
<p>Email:*<input type="text" id="email" placeholder="[email protected]">
<br>
<br>
Show Password:<input id="chk" name="chk" type="checkbox" onclick="validate()" />
<br>
<br>
<input type="button" value="Create!" name="Submit" onclick="pwFunction()">
</p>
<a href="create.html">Don't Have An Account? Create One!</a>
</fieldset>
</form>
<script>
function pwFunction() {
var password = document.getElementById('pass');
var lok = password.value.length >= 8;
var cpassword = document.getElementById('passwd');
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
return lok;
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}
}
</script>
It Only Runs The 'Your Password Must Have Eight Characters' Alert. Why Isn't It Running Both? Thanks For Any Answers, And Sorry For The Inconvenience.
3 Answers 3
There are a couple of error in your code / scripts:
Edit 1. Change the button to
<input type="submit" value="Create!" name="Submit" >
Edit 2. Use javascript validation on form tag
<form name = "logme" action="somewhere" onsubmit = "return pwFunction();">
This way the form is submitted only when the pwFunction() returns true.
Edit 3. Your javascript function should be:
function pwFunction() {
var password = document.getElementById('pass');
var cpassword = document.getElementById('passwd');
if (password.value.length < 8) {
alert('Your Password Must Have Eight Characters!');
return false;
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
return false;
}
else
{
return true;
}
}
Comments
Try
if(password.value !== cpassword.value) {
alert('Your Passwords Do Not Match!');
}
Comments
Like you did, the return statement is executed always, so it causes the function to stop execution and return a result. delete the return statement:
if (!lok) {
alert('Your Password Must Have Eight Characters!');
}
if(password.value != cpassword.value) {
alert('Your Passwords Do Not Match!');
}
Comments
Explore related questions
See similar questions with these tags.