表单一旦被错误检查破坏就不会提交

Form won't submit once error checking breaks it

本文关键字:提交 检查 错误 表单      更新时间:2023-09-26

我正在做一个项目,我有一些错误检查。但是,表单每次都想提交,所以我不得不中断提交。以下是我所做的。

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "order-form" }))
{
...
<input type="submit" name="btnSaveOpv@(item.Id)" value="@T("Admin.Common.Save")" id="btnSaveOpv@(item.Id)" class="adminButton" style="display: none;" onclick="SaveBtn(@item.Id);" />
...
    var originalIssuedQty = 0;
    function SaveBtn(id) {
    var quantity = parseInt($("#pvQuantity" + id).val());
    var issuedQty = parseInt($("#pvIssuedQty" + id).val());
    var stockQty = parseInt($("#hfStockQty" + id).val());
    var availableStockQty = stockQty + parseInt(originalIssuedQty);
    //Issued Quantity cannot exceed Quantity (you can't issue more than requested)
    if (issuedQty > quantity) {
    alert("Issued Quantity cannot exceed Quantity.");
    $("#order-form").submit(function (e) { e.preventDefault(); });
    return false;
    }
    //Make sure Issued Quantity is within Available Stock Quantity
    if (issuedQty > availableStockQty) {
    alert("There is not enough Products in Stock to issue this amount.");
    $("#order-form").submit(function (e) { e.preventDefault(); });
    return false;
    }
    //Present confirmation
    var result = confirm('@T("Admin.Common.AreYouSure")');
    if (!result) {
    $("#order-form").submit(function (e) { e.preventDefault(); });
    return false;
    }
    else {
    $("#order-form").submit(function (e) { this.submit(); });
    //$("#order-form").submit(function (e) { return true; });
    }
    }    
    ...
}

问题在这里。每当我尝试第一次提交而不触发任何错误检查时,事情就会正常工作。当我触发错误检查时,一切正常。但是,如果我修复错误并尝试再次提交,页面只是刷新。任何关于这方面的想法都会很有帮助。谢谢。

你把事情弄得太复杂了。

这是一个基本的模板,告诉你如何进行验证,以及如何在表单无效时停止提交:

$(function() {
  $("#order-form").submit(function (e) {
    var isValid = false;
    // Do your validation here and put the result in the variable isValid
    if ( !isValid ) {
      e.preventDefault(); // If the form is invalid stop the submit, otherwise proceed
    }
  });
});

每次调用$("#order-form").submit(function (e) { whatever });时,都要添加一个附加的处理函数。它不会删除您已经添加的处理程序。这可能就是为什么它坏了。

反复更改submit事件处理程序是一种混乱的方式。相反,您应该有一个处理提交事件的函数,该函数应该执行(或调用)错误检查,并在必要时使用preventDefault()(如ZippyV建议)。