0

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 submits when I use:

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

and when I use:

<form>
<input type="submit" onclick="checkPass();">
</form>

and no luck. Any ideas?

2
  • How are you attaching that event handler to your form? Commented Nov 18, 2010 at 22:08
  • Your code is a little confusing. Can you clarify the form you are trying to work with? Is this checkPass in your onsubmit function? Commented Nov 18, 2010 at 22:10

3 Answers 3

3

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()"
Sign up to request clarification or add additional context in comments.

Comments

2

If you are using xhtml make sure 'onsubmit' is lowercase.

<form onsubmit="return checkPass()" ... >

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.