Question

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!

Était-ce utile?

La solution

Where is .validate()?

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top