简体   繁体   English

将jQuery Validation插件与动态表单元素一起使用

[英]Using jQuery Validation Plugin with dynamic form elements

I have a page that contains multiple forms, and each form can contain any number of elements that have a common root in its name. 我有一个包含多个表单的页面,每个表单可以包含名称中具有相同根的任意数量的元素。 I'm trying to use this answer to validate a form when it's submitted, but I get a TypeError: a.data(...) is undefined error on jquery.validate.js . 我正在尝试使用此答案来验证表单,但提交时出现TypeError: a.data(...) is undefined jquery.validate.js上的TypeError: a.data(...) is undefined错误。 My code is below. 我的代码如下。

    var valForm = function(kit_id) {
        $('input[name^="kit_desc_"]').each(function() {
            $(this).rules("add", {
                required: true,
                messages: {
                    required: "Please enter a description"
                }
            });
        });

        $("#frm_" + kit_id).validate({
            errorElement: "div",
            errorPlacement: function(error, element) {
                $("#error_modal").html(error);
            }
        });

        if (! $("#frm_" + kit_id).valid()) {
            // a dialog box will appear listing the errors.
            $("#error_modal").dialog();
        }
    };

The function is called when a link is clicked. 单击链接时将调用该函数。

<a href="javascript:;" onclick="valForm(1);" class="button136">Save</a>

Any suggestions? 有什么建议么?

I think you have to call .validate() on the form before you can call .rules() on the inputs in that form. 我认为你必须调用.validate()在表格上,然后才能调用.rules()在该表单的输入。 You should also call .rules() only on the inputs in the form you're submitting. 您还应该仅在提交表单的输入上调用.rules()

var valForm = function(kit_id) {
    var form = $("#frm_" + kit_id);
    form.validate({
        errorElement: "div",
        errorPlacement: function(error, element) {
            $("#error_modal").html(error);
        }
    });

    form.find('input[name^="kit_desc_"]').each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "Please enter a description"
            }
        });
    });

    if (! form.valid()) {
        // a dialog box will appear listing the errors.
        $("#error_modal").dialog();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM