Vinee
Vinee

Reputation: 1654

How to validate clone elements in jQuery validation?

I am using bassistance.de/jquery-plugins

and this is default jQuery form validation service.

I am aware that question related to jQuery validation asked too many times but my problem is
little bit different.

I have one form with one file input and i am cloning like below

var picFields = $('#file').clone(true);

and appending into the form to upload multiple file.

while cloning i have class with 'required' name and adding the rule like

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

and initially validating like

$('#form').validate();  

its validating only the first element not all the dynamic added fields.

Upvotes: 4

Views: 6873

Answers (2)

mato gallardo
mato gallardo

Reputation: 96

Every input needs an unique name. The plugins fails to consider things like name="location[]", you have to add an index (correct would have been name="location[0]"). For cloned elements I get first the html "clone().html()" then I replace the [0] with a counter number i keep track Ex: .replace(/[0]/g, "["+cont+"]")

then I can safely append the generated html to the DOM and the plugin works as usual.

REMEMBER: JQUERY VALIDATE NEEDS AN UNIQUE NAME IN THE INPUT!! I pay myself with a lot of hours lost for this.

Upvotes: 5

Solve it !

What I used to do: after I clone the object, I called a function that creates the validation:

function add_another_form(){
     var new_form =  jQuery(".class").clone(true);
     new_form.appendTo(".parent");
     add_validation_for_forms();//attach again the validation !
}

function add_validation_for_forms(){
    jQuery(".class").validate({....})

But that was not working, so I just used a .each function in there, and it works now...

function add_validation_for_forms(){
    jQuery(".class").each(function(){
        jQuery(this).validate({....})

Upvotes: 0

Related Questions