Javascript onsubmit 方法不会停止提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12623244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:52:09  来源:igfitidea点击:

onsubmit method doesn't stop submit

javascripthtmlformsonsubmit

提问by Rita

My onsubmitis not working. My idea was to put some mandatory fields and, in order to achieve that, I was using the onsubmitmethod inside a form in HTML that called a JavaScript function.

onsubmit的不工作。我的想法是放置一些必填字段,为了实现这一点,我onsubmit在 HTML 表单中使用了该方法,该方法调用了 JavaScript 函数。

The idea was if all the mandatory fields were filled, the javascript function would return trueand it would move on to page /control/Cadastro.php. Otherwise, if any mandatory field was empty, it would return falseand it wouldn't move to page /control/Cadastro.php, staying in the current page until true.

这个想法是,如果所有必填字段都被填满,javascript 函数将返回true并移至 page /control/Cadastro.php。否则,如果任何必填字段为空,它将返回false并且不会移动到 page /control/Cadastro.php,停留在当前页面直到为真。

Unfortunately, the function does return falseif all the mandatory fields are not filled, as expected, but it still moves to page /control/Cadastro.php, even if it shouldn't.

不幸的是,false如果未按预期填充所有必填字段,该函数确实会返回,但它仍然会移动到 page /control/Cadastro.php,即使它不应该。

I'm going to cut off some code to make my point of view perceptible.

我将剪掉一些代码以使我的观点易于理解。

<!DOCTYPE html>
<html>
    <head>
        <script>
            function ValidateRequiredFields()
            {
                var message = new String('\nCampos obrigatórios:\n');
                var flag=new Boolean(1);
                var x=document.forms["theForm"]["nr_processoCA"].value;
                if (x==null || x==""){
                    message += '\nNo do processo\n'; 
                    flag = new Boolean(0);
                } 
                if (flag == false){
                    alert(message);
                }
                return flag;    
            }
        </script>
    </head>
    <body>
        <form name="theForm" onsubmit="return ValidateRequiredFields()" method="post" action="../control/Cadastro.php"> 
            No do Processo: <br>
            <input type="text" name="nr_processoCA" class="input-xlarge">
            <br>
            <div class="row-fluid" style="text-align:center;">
                <input type="submit" class="btn btn-primary btn-large" value="Gravar">
            </div>   
         </form>
    </body>
</html>

回答by Anoop

You should use preventDefaultinside your onsubmit function. I modified your code:

您应该preventDefault在 onsubmit 函数中使用。我修改了你的代码:

function ValidateRequiredFields()
{
    var message = new String('\nCampos obrigatórios:\n');
    var flag=new Boolean(1);


    var x=document.forms["theForm"]["nr_processoCA"].value;
    if (x==null || x==""){
        message += '\nNo do processo\n'; 
        flag = new Boolean(0);
    }

    if (flag == false){
        if(event.preventDefault){
            event.preventDefault();
        }else{
            event.returnValue = false; // for IE as dont support preventDefault;
        }
        alert(message);
    }

    return flag;
}

DEMO

演示

回答by Glenn Ferrie

To make this work, your ValidateRequiredFieldsfunction needs to return a boolean value. And then you should attach that method to the onSubmitevent. Remember, that for onsubmityou need to use the returnkeyword.

为了使这项工作,您的ValidateRequiredFields函数需要返回一个布尔值。然后你应该将该方法附加到onSubmit事件中。请记住,因为onsubmit您需要使用return关键字。

This code sample works:

此代码示例有效:

<!DOCTYPE html>
<html>
<head>
<script>
    function ValidateRequiredFields() {
        var message = new String('\nCampos obrigatórios:\n');
        var flag=1;

        var x=document.forms["theForm"]["nr_processoCA"].value;
        if (x==null || x==""){
            message += '\nNo do processo\n'; 
           alert(message);
           return false;
        }
        return true;
    }
</script>
</head>

<body>

<form name="theForm" method="post" action="../control/Cadastro.php" onSubmit="return ValidateRequiredFields()">


No do Processo: <br><input type="text" name="nr_processoCA" class="input-xlarge"><br>

<div class="row-fluid" style="text-align:center;">
    <input type="submit" class="btn btn-primary btn-large" value="Gravar">
</div>   

</form>

</body>
</html>

回答by volchkov

i suggest to put a button that will run the form if true:

我建议放置一个按钮,如果为真,它将运行表单:

 <input type='button' onclick="if (ValidateRequiredFields()) document.forms['theForm'].submit();" />

that's all....

就这样....

回答by limos

An object will always evaluate to true, even if it's a Boolean object with value false.

一个对象总是会被评估为真,即使它是一个值为假的布尔对象。

Put flag = trueat the top of the function, then flag = falseinstead of creating a Boolean.

放在flag = true函数的顶部,flag = false而不是创建一个布尔值。

回答by user3096163

I was having a similar problem. It turned out there was an error in my validation (nested a few functions deep) which was causing JavaScript to quit execution of the function before reaching a return statement. At which point it would just continue with the submit.

我遇到了类似的问题。结果证明我的验证中有一个错误(嵌套了几个函数很深),导致 JavaScript 在到达 return 语句之前退出函数的执行。此时它将继续提交。

My advise to anyone finding this page looking for an answer to "onsubmit method doesn't stop submit" is to step through your validation function with a fine tooth comb.

对于找到此页面并寻找“onsubmit 方法不会停止提交”的答案的任何人,我的建议是使用细齿梳逐步完成您的验证功能。

回答by user1766329

After looking around for an answer that worked for me I decided to just create a solution. The following code allows native HTML5 form validation to run before submitting or running another function (tested in Chrome). Make sure you return false after the function to prevent the form submission.

在四处寻找对我有用的答案后,我决定创建一个解决方案。以下代码允许在提交或运行其他功能(在 Chrome 中测试)之前运行原生 HTML5 表单验证。确保在函数之后返回 false 以防止表单提交。

<input type="submit" value="Submit" onclick='if (document.getElementById("mainForm").checkValidity()) { submitData(); return false;}' />