I am using the jQuery Validation plugin and trying to use the errorPlacement
callback function with a wildcard selector. I have tried countless permutations of the wildcard syntax with and without the .attr
method (and have tried several other methods) and and can't get it to work right.
I have read several dozen threads about wildcards, as well as api documentation but none address their use in a function like this where the use of 'element' is required. can't seem to get my head around it...
/*** This will work but only for the specified string ****/
if (element.attr("name") == "cdlradio1" )
I want to select all input elements beginning with 'cdlradio'
var $validator = $("#myform").validate({
errorPlacement: function(error, element) {
if (element.attr("[name^='cdlradio']"))
error.insertAfter(element.closest(".bootradlab"));
else
error.insertAfter(element);
}
Any help would be greatly appreciated.
This is not in the proper format...
if (element.attr("[name^='cdlradio']")) ...
Because, the .attr()
method is looking for an attribute as its only argument. Clearly, [name^='cdlradio']
is a selector, not an attribute. You don't need a selector since your target element is already selected by the element
argument.
You have to get the field name
and check to see if it contains your string...
if (element.attr('name').indexOf('cdlradio') >= 0) ...
"Wildcard" DEMO: http://jsfiddle.net/aBrL2/2/
BTW - ^=
is the "starts with" selector, not a wild-card. However, my solution above is a true wild-card as it doesn't care about position as long as the string occurs someplace. My answer can easily be converted to a "starts with" by changing the >=
operator into a ==
operator.
"Starts With" DEMO: http://jsfiddle.net/aBrL2/3/