用于停止表单提交的 JavaScript 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8664486/
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-24 06:58:23  来源:igfitidea点击:

JavaScript code to stop form submission

javascripthtmlforms

提问by Muhammad Imran Tariq

One way to stop form submission is to return false from your JavaScript function.

停止表单提交的一种方法是从 JavaScript 函数返回 false。

When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage();

单击提交按钮时,将调用验证函数。我有一个表单验证案例。如果满足该条件,我将调用一个名为returnToPreviousPage();的函数

function returnToPreviousPage() {
    window.history.back();
}

I am using JavaScript and Dojo Toolkit.

我正在使用 JavaScript 和Dojo Toolkit

Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page?

而是返回上一页,它提交表单。如何中止本次提交并返回上一页?

回答by Hemant Metalia

You can use the return value of the function to prevent the form submission

可以使用函数的返回值来阻止表单提交

<form name="myForm" onsubmit="return validateMyForm();"> 

and function like

和功能像

<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  { 
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler's parameter's returnValuefield to false to get it to work.

在 Chrome 27.0.1453.116 m 的情况下,如果上述代码不起作用,请将事件处理程序的参数的 returnValue字段设置为 false 以使其工作。

Thanks Sam for sharing information.

感谢山姆分享信息。

EDIT :

编辑 :

Thanks to Vikram for his workaround for if validateMyForm() returns false:

感谢 Vikram 的解决方法 if validateMyForm() 返回 false:

 <form onsubmit="event.preventDefault(); validateMyForm();">

where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

其中 validateMyForm() 是一个函数,如果验证失败则返回 false。关键点是使用名称事件。我们不能用于 egepeventDefault()

回答by Greg Guida

Use prevent default

使用防止默认

Dojo Toolkit

道场工具包

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

jQuery

jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

Vanilla JavaScript

原生 JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}

回答by Vikram Pudi

The following works as of now (tested in Chrome and Firefox):

以下工作截至目前(在 Chrome 和 Firefox 中测试):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns falseif validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

其中 validateMyForm() 是一个函数,false如果验证失败则返回。关键点是使用名称event。我们不能使用 for eg e.preventDefault()

回答by dku.rajkumar

Just use a simple buttoninstead of a submit button. And call a JavaScript function to handle form submit:

只需使用简单的button而不是提交按钮。并调用一个 JavaScript 函数来处理表单提交:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

Function within a scripttag:

script标签内的功能:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

You can also try window.history.forward(-1);

你也可以试试 window.history.forward(-1);

回答by Danial

Lots of hard ways to do an easy thing:

做一件简单的事情有很多困难的方法:

<form name="foo" onsubmit="return false">

回答by Gdba

All your answers gave something to work with.

你所有的答案都提供了一些有用的东西。

FINALLY, this worked for me: (if you dont choose at least one checkbox item, it warns and stays in the same page)

最后,这对我有用:(如果您没有选择至少一个复选框项目,它会发出警告并保持在同一页面中)

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <form name="helloForm" action="HelloWorld" method="GET"  onsubmit="valthisform();">
            <br>
            <br><b> MY LIKES </b>
            <br>
            First Name: <input type="text" name="first_name" required>
            <br />
            Last Name: <input type="text" name="last_name"  required />
            <br>
            <input type="radio" name="modifyValues" value="uppercase" required="required">Convert to uppercase <br>
            <input type="radio" name="modifyValues" value="lowercase" required="required">Convert to lowercase <br>
            <input type="radio" name="modifyValues" value="asis"      required="required" checked="checked">Do not convert <br>
            <br>
            <input type="checkbox" name="c1" value="maths"     /> Maths
            <input type="checkbox" name="c1" value="physics"   /> Physics
            <input type="checkbox" name="c1" value="chemistry" /> Chemistry
            <br>

            <button onclick="submit">Submit</button>

            <!-- input type="submit" value="submit" / -->
            <script>
                <!---
                function valthisform() {
                    var checkboxs=document.getElementsByName("c1");
                    var okay=false;
                    for(var i=0,l=checkboxs.length;i<l;i++) {
                        if(checkboxs[i].checked) {
                            okay=true;
                            break;
                        }
                    }
                    if (!okay) { 
                        alert("Please check a checkbox");
                        event.preventDefault();
                    } else {
                    }
                }
                -->
            </script>
        </form>
    </body>
</html>

回答by Isaac Abramowitz

I would recommend not using onsubmitand instead attaching an event in the script.

我建议不要使用onsubmit而是在脚本中附加一个事件。

var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
  submit.addEventListener("click", returnToPreviousPage);
} else {
  submit.attachEvent("onclick", returnToPreviousPage);
}

Then use preventDefault()(or returnValue = falsefor older browsers).

然后使用preventDefault()(或returnValue = false用于较旧的浏览器)。

function returnToPreviousPage (e) {
  e = e || window.event;
  // validation code

  // if invalid
  if (e.preventDefault) {
    e.preventDefault();
  } else {
    e.returnValue = false;
  }
}

回答by Phan Van Linh

Base on @Vikram Pudi answer, we can also do like this with pure Javascript

基于@Vikram Pudi 的回答,我们也可以使用纯 Javascript 来做到这一点

<form onsubmit="submitForm(event)">
    <input type="text">
    <input type="submit">
</form>

<script type="text/javascript">

    function submitForm(event){
        event.preventDefault();


    }
</script>

回答by Jesperai

Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:

Hemant 和 Vikram 的答案在 Chrome 中对我来说并不完全适用。event.preventDefault(); 无论验证通过或失败,脚本都会阻止页面提交。相反,我不得不移动 event.preventDefault(); 进入 if 语句如下:

    if(check if your conditions are not satisfying) 
    { 
    event.preventDefault();
    alert("validation failed false");
    returnToPreviousPage();
    return false;
    }
    alert("validations passed");
    return true;
    }

Thanks to Hemant and Vikram for putting me on the right track.

感谢 Hemant 和 Vikram 让我走上正轨。

回答by Dheeraj Nalawade

E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.

例如,如果您在表单上有提交按钮,为了停止其传播,只需编写 event.preventDefault(); 在点击提交按钮或输入按钮时调用的函数中。