I'm having issues validating some dynamic content. The closest I have come to finding a similar problem is this: jquery-validate-is-not-working-with-dynamic-content
My form is a basic form, enter name, email, phone etc. But there's this question "How many passengers?"
This is a select
and depending on how many passengers you select, I use jQuery to create more fields based on this amount using this:
$('select.travellers').attr('name','Number of travelers').on('click', function() {
var travellers = this.value; //On change, grab value
var dom = "";
for(var i = 0; i < travellers; i++){ //for 0 is less than travellers
dom += '<label>Full Name</label>';
dom += '<input type="text" name="FullName_'+i+'">';
dom += '<label>Food requirements</label>';
dom += '<select size= "0" name="Food Requiries_'+i+'" tabindex="-1" >
<option value="No pork">No pork</option>
<option value="Halal">Halal</option>
<option value="Food allergies">Food allergies</option>
<option value="Other">Other</option></select>';
}
$('.form_Additional').html(dom); //add dom into web page
});
The output is an input
field asking for the additional passenger name and a select
asking for their food requirements
How do I validate these newly created elements? This is what I have so far:
$(document).ready(function(e) {
//validation rule for select
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
//validate form
$("#FORMOB7DC24203803DC2").on("click", function(event){
$(this).validate({
rules: {
FullName:{
required: true
},
FullName_0:{
required: true
},
'Number of travelers':{
valueNotEquals: "Please select"
}
}
});
});
});
Is there a way to make this dynamic? Because this form allows for up to 30 passengers and I don't want to manually write in rules FullName_0
, FullName_1
, FullName_2
etc etc.
I added the rule FullName_0
and it doesn't validate so I don't know what I'm doing wrong.
note - simplified code for readability