简体   繁体   中英

Javascript Form Validation

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;
                          }
                        }  

The form still sumbit when i use:

<form onsumbit="checkPass();">
</form>

and when i user

<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()"

如果您使用的是xhtml,请确保“ onsubmit”为小写。

<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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM