Add Rules On Dynamic Form

2020-05-08 01:43发布

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!

2条回答
一夜七次
2楼-- · 2020-05-08 02:11

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.

查看更多
smile是对你的礼貌
3楼-- · 2020-05-08 02:17

Where is .validate()?

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

查看更多
登录 后发表回答