Here is my javascript code to check whether the user has entered values for username and password fields. When I run this, it shows me the correct alerting messages but the form is seems to be submitted even it returns false. Can someone helps me?
<script type="text/javascript">
function loginValidate(){
if (document.getElementById("username").value==''){
window.alert("Please enter your username");
if (document.getElementById("password").value==''){
window.alert("Please enter your username and password");
return false;
}
}
if (document.getElementById("password").value==''){
window.alert("Please enter your password");
return false;
}
return true;
}
</script>
<form onsubmit="loginValidate()">
<input type="submit" name="submit" id="submit" value="Login" />
</form
You need to return the value returned by the function to the handler:
<form onsubmit="return loginValidate()">
Also, do not give any form control a name or id of "submit" as it assign a reference to the control to the form's submit property, thereby masking the form's submit method (ie form.submit
references the control, so form.submit()
will fail).
There is rarely any need for a submit button to have a name or id, so:
<input type="submit" value="Login">
You can also clean up the logic a bit. If you pass a reference to the form to the function, getting the controls is easier:
<script>
function loginValidate(form){
if (form.username.value == ''){
window.alert("Please enter your username");
return false;
}
if (form.password.value == ''){
window.alert("Please enter your password");
return false;
}
return true;
}
</script>
<form onsubmit="return loginValidate(this)">
<table>
<tr><td>Username: <td><input type="text" name="username">
<tr><td>Password: <td><input type="password" name="password">
<tr><td colspan="2" style="text-align: right;><input type="submit" value="Login">
</table>
</form
Note that this sends the password in clear text so not particularly secure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.