Reputation: 4409
I'm trying to add the same rules to html input elements with this naming convention:
name="elements[1]"
name="elements[2]"
I'm using jQuery and jQuery Validation Plugin:
var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
element.rules('add', {
required: true,
number: true
});
But I'm afraid that element is not the kind of object jQuery expects for adding rules. I'm receiving:
Uncaught TypeError: Object #<HTMLInputElement> has no method 'rules'
Many thanks for any help.
Upvotes: 1
Views: 1987
Reputation: 57105
Use $(this)
instead of element
.
element
is HTML JavaScript Object.
to add rules you need jQuery Object i.e $(this)
var elements = $("#elementsFieldset :input");
$.each(elements, function(i, element) {
$(this).rules('add', {
required: true,
number: true
});
or even better
var elements = $("#elementsFieldset :input");
elements.each(function(){
$(this).rules('add', {
required: true,
number: true
});
Updated
Below code works for one element only if you want to apply rule for more than one element use .each()
as used in above example.
$("#elementsFieldset :input").rules("add", {
required:true,
number:true
});
Read jQuery Validation Plugin - adding rules that apply to multiple fields commented by Sparky
Upvotes: 3
Reputation: 40639
Try this,
$.each(elements, function(i, element) {
$(this).rules('add', {// use $(this) instead of element
required: true,
number: true
});
or try it simply,
$("#elementsFieldset :input").rules("add", {
required:true,
number:true
});
You can add rule
on a class
See jQuery Validation using the class instead of the name value
Upvotes: 2