Gags Gags - 2 months ago 13
jQuery Question

Vaildate dynamic added array inputs - jQuery Validate

Good Afternoon,

Dynamic Fields are being added with jQuery and i am using jQuery Validate plugin to validate form.

Code to create dynamic fields depend on number of selected options from selectbox.

$('#ids_noct').on('change', function() {
var tsd = ( this.value );
for(var j=1; j <= tsd; j++) {
$("#t").append("<input name="name_ct[]" id="id_ct' + j + '" type="text"
class="form-control" placeholder="Add Variant' + j + ' Name" >");
}
});


jQuery code to validate:

$("#formsx").validate({
rules: {
"name_ct[]": {required: true}
}


But with this only First field is getting validated not all.


Suppose if i have added 5 fields then 1 out of 5 is validates, not all.


Also, i want to know that can i upload image using PHP and jQuery Validate.
});

Answer Source

You have a couple basic problems in your code. First, your append call doesn't have it's quotes set correctly - you can't start with a double quote and then include double quotes inside of it, it will throw an error. So, your call should look more like this:

$("#t").append('<input name="name_ct[]" id="id_ct' + j + '" type="text" class="form-control" placeholder="Add Variant' + j + ' Name" >');

Secondly, you can't have inputs of type text with the same name attribute. So if you have 5 of these name_ct inputs, they each need to have their own name:

$("#t").append('<input name="name_ct'+j+'" id="id_ct' + j + '" type="text" class="form-control" placeholder="Add Variant' + j + ' Name" >');

Finally, when you add a new field after $.validate has been called, you must also update the rules for it:

$('#ids_noct').on('change', function() {
  var tsd = ( this.value );
  for(var j=1; j <= tsd; j++) {
     $("#t").append('<input name="name_ct'+j+'" id="id_ct' + j + '" type="text" class="form-control" placeholder="Add Variant' + j + ' Name" >');
     $('#id_ct'+j).rules('add',{
       required:true
     });
  }
});

Not knowing what exactly you want to do with these name_ct values, I can't say how you should recombine them, but in the submitHandler of $.validate, you can change the data however you need before doing a $.post.

See it working here: http://jsfiddle.net/ryleyb/6syqa60d/