JavaScript Form Validation when false
This is really bothering me. I just want the form to not submit if the function returns false. Here is the script.
function checkPass(){
var pass1 = document.getElementById('pass');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirmMessage');
var goodColor = "#224466";
var badColor = "#900000";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
return true;
}else{
pass2.style.backgroundColor = badColor;
return false;
}
开发者_如何学C }
The form still submits when I use:
<form onsumbit="checkPass();">
</form>
and when I use:
<form>
<input type="submit" onclick="checkPass();">
</form>
and no luck. Any ideas?
Use this on the onsubmit event of your form:
onsubmit="return checkPass()"
Or this one for your Submit button (the input tag):
onclick="return checkForm()"
If you are using xhtml make sure 'onsubmit' is lowercase.
<form onsubmit="return checkPass()" ... >
As M2X says, you need to use
<form onsubmit="return checkPass();">
The reason is that when you assign an event handler as an attribute that way, what actually happens internally is that a new anonymous function is created wrapped around the code in the attribute, and that function needs to return the value that will prevent or allow the form submission.
So your original onsubmit
attribute will be turned into:
function() {
checkPass();
}
which executes the checkPass
function but discards its return value. By including the return
in the attribute, it will be turned into:
function() {
return checkPass();
}
which will return the value returned to it by the checkPass
function, thereby achieving the desired effect.
精彩评论