停止提交表单,使用 Jquery

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

Stop form from submitting , Using Jquery

jqueryasp.net-mvc-3validationpreventdefault

提问by Antarr Byrd

I'm trying to stop my form from submitting if a validation fails. I tried following this previous postbut I doesn't work for me. What am I missing?

如果验证失败,我试图阻止我的表单提交。我尝试按照上一篇文章进行操作,但对我不起作用。我错过了什么?

<input id="saveButton" type="submit" value="Save" />
<input id="cancelButton" type="button" value="Cancel" />
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("form").submit(function (e) {
            $.ajax({
                url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
                data: { id: '@Model.ClientId' },
                success: function (data) {
                    showMsg(data, e);
                },
                cache: false
            });
        });
    });
    $("#cancelButton").click(function () {
        window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
    });
    $("[type=text]").focus(function () {
        $(this).select();
    });
    function showMsg(hasCurrentJob, sender) {
        if (hasCurrentJob == "True") {
            alert("The current clients has a job in progress. No changes can be saved until current job completes");
            if (sender != null) {
                sender.preventDefault();
            }
            return false;
        }
    }

</script>

回答by Selvakumar Arumugam

Again, AJAX is async. So the showMsg function will be called only after success response from the server.. and the form submit event will not wait until AJAX success.

同样,AJAX 是异步的。所以 showMsg 函数只有在服务器响应成功后才会被调用......并且表单提交事件不会等到 AJAX 成功。

Move the e.preventDefault();as first line in the click handler.

e.preventDefault();在点击处理程序中移动as 第一行。

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...

See below code,

看下面的代码,

I want it to be allowed HasJobInProgress == False

我希望它被允许 HasJobInProgress == False

$(document).ready(function () {
    $("form").submit(function (e) {
        e.preventDefault(); //prevent default form submit
        $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data);
            },
            cache: false
        });
    });
});
$("#cancelButton").click(function () {
    window.location = '@Url.Action("list", "default", new { clientId = Model.ClientId })';
});
$("[type=text]").focus(function () {
    $(this).select();
});
function showMsg(hasCurrentJob) {
    if (hasCurrentJob == "True") {
        alert("The current clients has a job in progress. No changes can be saved until current job completes");
        return false;
    } else {
       $("form").unbind('submit').submit();
    }
}

回答by Arjun Raj

use this too :

也用这个:

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault()is not supported in IE( some versions ). In IE it is e.returnValue = false

IE(某些版本)不支持Becoz e.preventDefault()。在 IE 中它是e.returnValue = false

回答by Sandeep

A different approach could be

一种不同的方法可能是

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

回答by Downpour046

Try the code below. e.preventDefault() was added. This removes the default event action for the form.

试试下面的代码。 e.preventDefault() 已添加。这将删除表单的默认事件操作。

 $(document).ready(function () {
    $("form").submit(function (e) {
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
        });
        e.preventDefault();
    });
});

Also, you mentioned you wanted the form to not submit under the premise of validation, but I see no code validation here?

另外,您提到您希望表单在验证的前提下不提交,但我在这里没有看到代码验证?

Here is an example of some added validation

这是一些添加验证的示例

 $(document).ready(function () {
    $("form").submit(function (e) {
      /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */
    if(!$('#inputID').val()){ 
       e.preventDefault(); // This will prevent the form submission
     } else{
        // In the event all validations pass. THEN process AJAX request.
       $.ajax({
            url: '@Url.Action("HasJobInProgress", "ClientChoices")/',
            data: { id: '@Model.ClientId' },
            success: function (data) {
                showMsg(data, e);
            },
            cache: false
       });
     }


    });
 });

回答by keivan kashani

This is a JQuery code for Preventing Submit

这是防止提交的 JQuery 代码

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });