jquery validate plugin on dynamic form inputs not working

When using one of the methods from this plugin, like .rules(), and targeting more than one element, like a class, you must also use the jQuery .each() method.

$('.work_emp_name').each(function () {
    $(this).rules("add", {
        required: true
    });
});

And you cannot use .rules() on elements that don’t yet exist in the DOM. Simply move the .rules() method to inside the function that creates your new inputs.

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));
    counter += 1;
    $('.work_emp_name').each(function () { 
        $(this).rules("add", {
            required: true
        });
    });
});

Working DEMO: http://jsfiddle.net/Yy2gB/10/


However, you can make it more efficient by only targeting the one new field, instead of all fields with the work_emp_name class.

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));   // <- add new field
    $('input[name="work_emp_name['+counter+']"]').rules("add", {  // <- apply rule to new field
        required: true
    });
    counter += 1;
});

Working DEMO: http://jsfiddle.net/Yy2gB/11/


Both of my examples above are for adding rules to the dynamically created fields. You’ll still need to declare any rules for your static fields upon dom ready as follows…

$("#work_form").validate({
    rules: {
        "work_emp_name[0]": {
            required: true
        }
    }
});

Leave a Comment