【问题标题】:form submits although onClick should return false表单提交虽然 onClick 应该返回 false
【发布时间】:2014-10-30 11:59:16
【问题描述】:

我已经检查了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 应该阻止它,不是吗?

【问题讨论】:

    标签: javascript html forms


    【解决方案1】:

    doSomething() 需要 return 语句。最后一行应该是:

    return formValidation();
    

    【讨论】:

      【解决方案2】:

      试试-

      1. 添加“事件”作为 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;
                }
        }
        

      【讨论】:

        【解决方案3】:

        我认为你应该使用

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-22
          • 1970-01-01
          • 2013-01-14
          • 2021-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-20
          相关资源
          最近更新 更多