I'm trying to add validation rules on a form that is dynamically populated, depending on a JSON response from a back-end. I'm using jQuery 1.9.1 and jQuery Validation plugin.

function getItems(Id) {
    $.ajax({
            url: ...
            success: function (items) {
                buildForm(items);
            }
            error: ...
}

function buildForm(items) {
    $form = $('#testForm');
    $form.empty();
    $.each(items, function(i, item) {

        $form.append('<input type="text"' +
        'id="' + item.Id + '"' +
        'name="' + item.Name + '"' +
        'value="' + item.Default + '"' +
        ' />');
        $form.append('<br />');

        $('#' + item.Id).rules("add", { required:true,email:true }) // error!
    });
}

jQuery(function ( $ ) {
    getItems(1 //just an Id);
});

Error: Uncaught TypeError: Cannot read property 'settings' of undefined

I'm new to JavaScript surely this is not the smartest way to go. HTML not reported, it's just an empty form. I think the DOM is not ready for the rules selection, but I really don't know how to handle this, 'cause I must use success callback and I'm not inside DOM ready function. Any suggestions are welcome!

有帮助吗?

解决方案

Where is .validate()?

You cannot call plugin method rules("add") until sometime after the plugin has been initialized with .validate().

其他提示

I think the error is thrown from the validator plugin,

var settings = $.data(element.form, "validator").settings;

May be the 'id' is not referred properly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top