I have a form where blocks of HTML are added dynamically when someone wishes (for example) to “Add Another Adult” to a family.
I want each field to have a unique name, so I’m using a counter: the first name field for the first adult is ‘firstName1,’ for the second ‘firstName2,’ and so on.
Because I want to add custom messages to the fields (and the Validate plugin doesn’t have a messages() method), I’m trying to add the rules immediately after the HTML is added to the DOM.
This works fine for text inputs, but throws an error for select elements — ‘TypeError: d is undefined’.
For example:
$("input[name='city" + counter + "']").rules("add", {required:true, messages: {required:"Please enter a city."
}});
… works fine. But …
$("input[name='state" + counter + "']").rules("add", {required:true, messages: {required:"Please enter a state."
}});
… which identifies a select box, throws the error.
The behavior is consistent. There are several selects which are added, and adding a rule to any of them in the manner shown above throws the error.
I’ll mention that all select boxes have an initial option with a value of “”, so the required validation should work properly.
But of course, it never gets a chance. The error is thrown when the rule is added.
Does anyone have any idea why this might be happening?
For selects you should use
select[name=foo]instead ofinput[name=foo]: