停止表单提交,使用Jquery

Ant*_*yrd 54 validation jquery preventdefault asp.net-mvc-3

我试图阻止我的表单提交验证失败.我试过按照上一篇文章,但我不适合我.我错过了什么?

<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>
Run Code Online (Sandbox Code Playgroud)

Sel*_*gam 103

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

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

$("form").submit(function (e) {
      e.preventDefault(); // this will prevent from submitting the form.
      ...
Run Code Online (Sandbox Code Playgroud)

见下面的代码,

我希望它允许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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Arj*_*Raj 15

也用这个:

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你使用jQuery,你可以安全地使用`e.preventDefault()`.jQuery将关注x-browser的兼容性. (10认同)