简体   繁体   English

JavaScript 停止表单提交的代码

[英]JavaScript code to stop form submission

One way to stop form submission is to return false from your JavaScript function.停止提交表单的一种方法是从您的 JavaScript function 返回 false。

When the submit button is clicked, a validation function is called.单击提交按钮时,将调用验证 function。 I have a case in form validation.我有一个表单验证案例。 If that condition is met I call a function named returnToPreviousPage();如果满足该条件,我将调用名为returnToPreviousPage() 的 function;

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

I am using JavaScript and Dojo Toolkit .我正在使用 JavaScript 和Dojo 工具包

Rather going back to the previous page, it submits the form.它不是返回到上一页,而是提交表单。 How can I abort this submission and return to the previous page?我怎样才能中止这次提交并返回到上一页?

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 returnValue field 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 为 validateMyForm() 返回 false 的解决方法:

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

where validateMyForm() is a function that returns false if validation fails.其中 validateMyForm() 是一个在验证失败时返回 false 的函数。 The key point is to use the name event.关键是使用name事件。 We cannot use for egepreventDefault()我们不能用于 egepreventDefault()

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();
    });
}

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 false if validation fails.其中 validateMyForm() 是一个在验证失败时返回false的函数。 The key point is to use the name event .关键点是使用名称event We cannot use for eg e.preventDefault() .我们不能使用例如e.preventDefault()

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>

Just use a simple button instead of a submit button.只需使用一个简单的button而不是提交按钮。 And call a JavaScript function to handle form submit:并调用一个 JavaScript 函数来处理表单提交:

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

Function within a script tag: script标签内的函数:

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

You can also try window.history.forward(-1);你也可以试试window.history.forward(-1);

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

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

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>

I would recommend not using onsubmit and 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 = false for 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;
  }
}

Lets say you have a form similar to this假设您有一个类似于此的表格

<form action="membersDeleteAllData.html" method="post">
    <button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>

Here is the javascript for the confirmAction function这是confirmAction函数的javascript

<script type="text/javascript">
    function confirmAction(e)
    {
        var confirmation = confirm("Are you sure about this ?") ;

        if (!confirmation)
        {
            e.preventDefault() ;
            returnToPreviousPage();
        }

        return confirmation ;
    }
</script>

This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.这适用于 Firefox、Chrome、Internet Explorer(edge)、Safari 等。

If that is not the case let me know如果不是这样,请告诉我

Eg if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault();例如,如果您在表单上有提交按钮,为了停止它的传播,只需编写 event.preventDefault(); in the function which is called upon clicking submit button or enter button.在单击提交按钮或输入按钮时调用的函数中。

Simply do it....干脆做吧......

<form>
<!-- Your Input Elements -->
</form>

and here goes your JQuery这里是你的 JQuery

$(document).on('submit', 'form', function(e){
    e.preventDefault();
    //your code goes here
    //100% works
    return;
});

Hemant and Vikram's answers didn't quite work for me outright in Chrome. Hemant 和 Vikram 的答案在 Chrome 中并不完全适合我。 The event.preventDefault(); event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation.无论是否通过验证,脚本都会阻止页面提交。 Instead, I had to move the event.preventDefault();相反,我不得不移动 event.preventDefault(); into the if statement as follows:进入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 让我走上正轨。

禁用提交按钮也有助于防止表单提交。

<input style="display:none" type="submit" disabled>

Even though it seems obvious it should be noted that you will also have to then submit your form if the validation is good to go if you block submitting with prevent default.尽管看起来很明显,但应该注意的是,如果您使用阻止默认值阻止提交,如果验证顺利进行,您还必须提交您的表单。 I provided a complete example below of validating doc type and then submitting if its the right doc type.我在下面提供了一个完整的示例来验证文档类型,然后提交是否正确的文档类型。

<h2>Document Upload</h2>
<script>
var CanContinue = false;

function validateMyForm()
{
if(CanContinue == false)
  { 
    alert("You must upload a PDF, PNG, or JPG of your document.");


return false;

  }
  document.getElementById("myForm").submit();

  return true;
}

function getFileNameWithExt(event) {

  if (!event || !event.target || !event.target.files || event.target.files.length === 0) {
return;
  }

  const name = event.target.files[0].name;
  const lastDot = name.lastIndexOf('.');

  const fileName = name.substring(0, lastDot);
  const ext = (name.substring(lastDot + 1)).toUpperCase();
    if (ext =="JPG") {
    extension.value = "image/jpeg";
    CanContinue = true;

} else if (ext =="JPEG") {
  extension.value = "image/jpeg";
  CanContinue = true;

} else if (ext =="PNG") {
  extension.value = "image/png";
  CanContinue = true;

} else if (ext =="PDF") {
  extension.value = "application/pdf";
  CanContinue = true;

} else {
  alert("You must upload a PDF, PNG, or JPG of your document.");
  CanContinue = false;
}

  outputfile.value = fileName;


}

</script>


                <form method="post" id="myForm" action="/wheregoing" enctype="multipart/form-data" onsubmit="event.preventDefault(); validateMyForm();">
                
                Please upload a JPG, PNG, or PDF of the front of the document.
                <input id='inputfile' type="file" name="dafile" onChange='getFileNameWithExt(event)' required>
               
             <input id='extension' type='hidden' name='ContentType' value="">
                <input type="submit">
                </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM