Reset required fields - jQuery

六眼飞鱼酱① 提交于 2019-12-12 15:24:05

问题


I have some fields that I'm requiring depending on which button is clicked. The behavior I'm seeing though is not what I would expect nor desire. When I click one of the buttons, it sets the required fields as I'd like, but then if I click another button, it doesn't reset them for some reason.

Code is below. Thanks for any help you can provide:

function makeAllRequired() {
        $("#SomeForm").validate({
            rules: {
                StartDate: {
                    required: true,
                    date: true
                },
                Name: {
                    required: true
                }

            },
            errorElement: "div"
        });
    }

    function makeSomeRequired() {
        $("#SomeForm").validate({
            rules: {
                StartDate: {
                    required: true,
                    date: true
                }
            },
            errorElement: "div"
        });
    }

    $(document).ready(function () {
        $("#SomeButtonOne").click(function () {
            makeAllRequired();
            $("#SomeForm").attr("action", "/here/there");
            $("#SomeForm").submit();
        });
$("#SomeButtonTwo").click(function () {
            makeSomeRequired();
            $("#SomeForm").attr("action", "/here/elsewhere");
            $("#SomeForm").submit();
        });
});

回答1:


Try reseting the form before setting new required items: http://docs.jquery.com/Plugins/Validation/Validator/resetForm




回答2:


I'm not 100% sure but try removing the rules first before you apply new ones

function makeAllRequired() {
    $("#SomeForm").rules("remove");
    $("#SomeForm").validate({
        rules: {
            StartDate: {
                required: true,
                date: true
            },
            Name: {
                required: true
            }

        },
        errorElement: "div"
    });
}

function makeSomeRequired() {
    $("#SomeForm").rules("remove");
    $("#SomeForm").validate({
        rules: {
            StartDate: {
                required: true,
                date: true
            }
        },
        errorElement: "div"
    });
}


来源:https://stackoverflow.com/questions/6047664/reset-required-fields-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!