0

back当他按下按钮到上一页时,我正在使用 Javascript 将用户重定向。我碰巧在同一页面上使用了 JQuery 验证插件,它在按下按钮时验证表单。当表单出现错误时它可以正常工作,如果表单的所有字段都没有任何错误,则它无法重定向,并且再次重新加载相同的页面。

我试图取消在ignore表单上使用的验证,但它不起作用。

这就是我的做法:

$("#btnBack").click(function () {
         $("aspnetForm").validate().cancelSubmit = true;
        SaveEmployeeInfo();
    });

这是表单验证器:

$("#aspnetForm").validate({
        rules: {
            txtGross: {
                required: true,
                number: true
            },
            ddlPay: {
                required: true,
                notEqual: "0"
            },
            ddlTax: {
                required: true,
                notEqual: "0"
            }
        },
        ignore: ".ignore",
    });

下面是我如何添加一个方法来比较值:

`//It is called for each of the required field in the aspnetForm
    $.validator.addMethod("notEqual", function (value, element, param) {
            return this.optional(element) || value !== param;
    }, "Please choose a value!");

这是我为保存员工信息而调用的函数:

function SaveEmployeeInfo() {
    var employee = GetEmployee();
    defaulted = false;
    $.ajax({
        type: "POST",
        url: window.location.protocol + '//' + window.location.host + window.location.pathname + "/SaveEmployeeInfo",
        data: $.toJSON({
            saveObject: {
                //all of the employee related information here
            }
        }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data, st) {
            if (st == 'success' && data.d != null) {
                if (data.d != "undefined") {

                    if (data.d) {
                        window.location = window.location.protocol + '//' + window.location.host + "EmployeeInfo.aspx";
                    }
                    else {
                        ShowMessage("Cannot redirect to new employee.");
                    }
                }
            }
        },
        error: function (msg) {
            if (!String.isNullOrEmpty(msg.responseText))
                ShowMessage(msg.responseText);
        }
    });

    return false;
}

我想避免在back按下按钮时调用任何类型的验证器,以便我可以重定向到相应的页面。

4

2 回答 2

0

要在仍然使用提交按钮的同时跳过验证,请在该输入中添加一个 class="cancel"。

 <input type="submit" name="submit" value="Submit"/>
 <input type="submit" class="cancel" name="cancel" value="Cancel"/>

请参阅http://jqueryvalidation.org/reference查找“在提交时跳过验证”

于 2013-10-02T11:36:37.623 回答
0

在尝试了可能的cancel选项之后ignore,我解决了另一种方法,即如果不避免则通过验证器。我使用boolean变量来做到这一点。

我是这样做的:

$("#btnBack").click(function () {
        backClick = true;
        SaveEmployeeFinancials();
    });

$.validator.addMethod("notEqual", function (value, element, param) {
        return (!backClick) && (this.optional(element) || value !== param);
    }, "Please choose a value!");

每当按下后退按钮时,该函数将返回 `false,从而将我的重定向呈现到另一个页面。

于 2013-10-03T05:11:58.343 回答