RHPT
RHPT

Reputation: 2650

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. 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?

Upvotes: 1

Views: 1172

Answers (1)

Barmar
Barmar

Reputation: 782785

I think you have to call .validate() on the form before you can call .rules() on the inputs in that form. You should also call .rules() only on the inputs in the form you're submitting.

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();
    }
};

Upvotes: 2

Related Questions