Reputation: 67
I'm trying to validate my form so that if the user doesn't enter the username or the password, he isn't allowed to login to the website. For some reason, when I do enter both the username and password fields, and click login, the login.html page doesn't appear. Any help?
<script>
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
<form id="loginform" name="loginform" method="post">
<div>
<label hidden> Username</label>
<input type= "text" class="text" placeholder="Username" title="Username" name="username">
<span id="usernameError"></span>
<label hidden> Password </label>
<input type= "password" class="text" placeholder="Password" title="Password" name="password">
<span id="passwordError"></span>
<a href="" class="anchor-float">Forgot password?</a>
</div>
<div class="button-container">
<a href="login.html" target="_blank"> <input type= "submit" value="Login" class="login"/>
</a>
<input type= "button" value="Sign up" class="login signup"/>
</div>
</form>
Upvotes: 1
Views: 53
Reputation: 65853
You had your submit button wrapped in an a
element that was pointing to login.html
, which is not how to properly redirect after a form submission. This will also cause problems with handling events because of event bubbling and/or capturing.
In actuality, you haven't specified where the form should send its data to in your form
tag:
<form id="loginform" name="loginform" method="post">
Which (by default) means that the form will send its data to the current page (causing the same page to reload, but have the form data accessible to it in this updated load).
To send the data to a different page/resource, the form needs to have an action
attribute which specifies the path to the destination:
<form id="loginform" name="loginform" method="post" action="login.html">
See this for details on submitting forms.
Stack Overflow's code snippet environment doesn't allow for form submissions, but check out this Fiddle which has an updated version of your code that works.
Upvotes: 2