JavaScript/JQuery表单验证运行两次

JavaScript/JQuery form validation runs twice

本文关键字:两次 运行 JQuery 表单 验证 JavaScript      更新时间:2024-04-08

我有一个JavaScript函数正在转换为JQuery,它在提交前检查表单。

function CheckRegistrationDetails(userId) {

    var ddl = document.getElementById('<%= cboDestination.ClientID %>');
    var toId = ddl.options[ddl.selectedIndex].value;

    if (toId === "0") {
        $("#<%= lblCheckMessage.ClientID %>").html("Please the area you wish to register your items.");
        return false;}
    var u1 = document.getElementById('<%= txtItem1.ClientID %>').value.replace(/,/g, "");
    var u2 = document.getElementById('<%= txtItem2.ClientID %>').value.replace(/,/g, "");
    var u3 = document.getElementById('<%= txtItem3.ClientID %>').value.replace(/,/g, "");
    var u4 = document.getElementById('<%= txtItem4.ClientID %>').value.replace(/,/g, "");
    var u5 = document.getElementById('<%= txtItem5.ClientID %>').value.replace(/,/g, "");
    if (i1 === "") {
        i1 = "0";
    }
    if (i2 === "") {
        i2 = "0";
    }
    if (i3 === "") {
        i3 = "0";
    }
    if (i4 === "") {
        i4 = "0";
    }
    if (i5 === "") {
        i5 = "0";
    }

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "Register.aspx/RegisterItems",
        data: "{userId: " + userId + ", toLocationId: " + toId + ", item1: " + i1 + ", item2: " + i2 + ", item3: " + i3 + ", item4: " + i4 + ", item5: " + i5 + "}",
        success: function (response) {
            if (response.d === 1) {
                $("#<%= lblCheckMessage.ClientID %>").html("You are trying to register more items than you have");
                alert("false");
                return false;
                                }
            if (response.d === 0) {
                $("#<%= lblCheckMessage.ClientID %>").html("You do not have enough credits to register these items!");
                alert("false");
                return false;
            }
            if (response.d === 2) {
                alert(confirm("Are you sure you dont want to register all your items?"));
                return confirm("Are you sure you dont want to register all your items?");
            }
            alert("true");
            return true;
        },
        fail: function () {
            alert("false fail");
            return false;
        }
    });
    alert("false default");
    return false;
} 

和按钮连接

if (!IsPostBack)
{
    cmdMakeRegistration.Attributes.Add("OnClick", "return CheckRegistrationDetails(" + userToken.UserId + ");");
}

当我试图提交一份有效的表格时,我会收到两个alert框。第一个是false default,第二个是true。表单未提交。

我被困在为什么我会收到两个警报

您正在执行一个成功的ajax请求,生成第二个警报(稍后会出现),但在验证器底部有一个流氓(而不是漂亮的,不要碰我,来自X-men的流氓)警报:

alert("false default");

您的代码总是返回false,从而禁止发送表单,但是Ajax调用会被发送并成功。