user3352472
user3352472

Reputation: 99

form submits although onClick should return false

I already checked How to prevent form from being submitted? but it did not help.

I have a register form with some input and a submit button

<script src="formValidation.js"></script> 
<script src="md5.js"></script>
<script language="javascript">
function doSomething() {   
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation();}


<form name="registration" action="/Arnito_test/Register" method="post"  >
<input onClick="return doSomething();" type=submit>

formValidation.js:

function formValidation() {
    ...
        if (registration.userpass.value == registration.username.value) {
            alert("Error: Password must be different from Username!");
           document.registration.userpass.focus();
            return false;
        }
...}

If I force this alert, it appears, but the form submits anyway. the return false should block it, no?

Upvotes: 0

Views: 172

Answers (3)

hzycaicai2012
hzycaicai2012

Reputation: 1

I think you should use

<input onSubmit="return doSomething();" type=submit>

Upvotes: 0

TamarG
TamarG

Reputation: 3570

Try -

  1. Add "event" as a parameter that doSomething gets

  2. Send it to formValidation

  3. Add event.preventDefault();

    function doSomething(event) 
    {   
       str = document.registration.userpass.value;
       str2 = document.registration.userpass2.value;
       document.registration.response.value = MD5(str);
       document.registration.response2.value = MD5(str2);
       document.registration.userpass.value="";
       document.registration.userpass2.value="";
       formValidation(event);
    
    }
    
    function formValidation(event) {
                    if (registration.userpass.value == registration.username.value) {
                alert("Error: Password must be different from Username!");
                document.registration.userpass.focus();
                event.preventDefault();
                return false;
            }
    }
    

Upvotes: 0

Barmar
Barmar

Reputation: 781626

doSomething() needs a return statement. The last line should be:

return formValidation();

Upvotes: 3

Related Questions