表单提交虽然onClick应该返回false

时间:2014-10-30 11:59:16

标签: javascript html forms

我已经检查了How to prevent form from being submitted?,但没有帮助。

我有一个带有输入和提交按钮的注册表单

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

如果我强制显示此警报,则会显示,但表单仍会提交。 return false应该阻止它,不是吗?

3 个答案:

答案 0 :(得分:3)

doSomething()需要return声明。最后一行应该是:

return formValidation();

答案 1 :(得分:0)

尝试 -

  1. 添加&#34;事件&#34;作为doSomething获取的参数

  2. 将其发送至formValidation

  3. 添加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;
            }
    }
    

答案 2 :(得分:0)

我认为你应该使用

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