1

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.

Jumpa
  • 4,319
  • 11
  • 52
  • 100
  • possible duplicate of [jQuery Validation Plugin - adding rules that apply to multiple fields](http://stackoverflow.com/questions/8829030/jquery-validation-plugin-adding-rules-that-apply-to-multiple-fields) – Sparky Oct 07 '13 at 16:26

2 Answers2

3

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

jQuery Validation Plugin

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • 1
    Ok for the long version. The short version appended validation only for the first element of the list...really don't know why if it's only sintax matter. – Jumpa Oct 07 '13 at 16:17
  • 1
    Your second version is incorrect. jQuery Validate's methods require the `.each()` method in this context. See option 2b in this answer: http://stackoverflow.com/a/9056425/594235 – Sparky Oct 07 '13 at 16:18
2

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

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • Your second version is incorrect. jQuery Validate's methods require the `.each()` method in this context. See option 2b in this answer: http://stackoverflow.com/a/9056425/594235 – Sparky Oct 07 '13 at 16:19