<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
4 Answers 4
Just a couple things are off, but it's almost there:
- The
onsubmithandler is used at the form level. Either move theonsubmitto the<form>element or change it to anonclickevent for the<input>element. - In order to reference the text fields the way you are, the
<form>element also needs anameattribute. i.e.name="loginForm"
1 Comment
onsubmit to the <form> element will still allow the enter key to submit the login. @Charly's answer reminded me of this.you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Comments
Do this:
- Remove onsubmit from button add it to form.
- Change
idof form toname. - In the
onsubmitof form appendreturn false;. - Remove
return false;from the if statements. Change
document.loginFormline to this:document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
Comments
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).
Comments
Explore related questions
See similar questions with these tags.