I am trying to create a very simple login form that requires the user to input a password and a username. If the user does not input a username or a password then i want an alert to pop up informing the user that he needs to input a username or a password and the page will not continue on to the welcome page. however this is not working......i dont get any alert pop up and also i am redirected to the welcome page automatically after i hit 'sign in' i just dont understand what the issue is. Any help would be very much appreciated and thank you in advance.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script type = "text/javascript">
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
return false;
else
{
true;
}
}
</script>
</head>
<body>
<form onsubmit = "return validate()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>
1 Answer 1
The problem is that on the onsubmit event on the form, you are returning "validate()", which is not a real function.
Instead, replace that bit, in the onsubmit attribute, to onsubmit="return login()", since that appears to be your replacement for the validate function.
Secondly though, in the login function itself, for most browsers you also need to call event.preventDefault(), right before return false (or perhaps instead of). Also, there was a } missing in the login function, also causing an error.
The fixed code should be
function login()
{
var username = document.getElementById("name");
var password = document.getElementById("pass");
if (username.value.trim() == "")
{
alert ("please enter a username or password");
event.preventDefault();
return false;
}
else if (password.value.trim() == "")
{
alert ("please enter a password");
event.preventDefault();
return false;
}
else//this part is also completely extraneous,there's no reason to have it, it should work the same either way
{
true;
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form onsubmit = "return login()" action = "welcome.html">
<input id= "name" placeholder= "Username" type= "text"/><br><br>
<input id= "pass" placeholder= "Password" type= "password"/><br><br>
<button type = "submit">SIGN IN</button>
</form>
</body>
</html>
validate()as the function foronSubmitwhen your function is calledlogin. Second, you havetrue;isntead ofreturn true;in your else statement.