1

In the code below the function which must determine whether the field is required does not work. The code relates to a website for which some text fields ('person_item') and checkboxes ('chckbox') are created dynamiccally followed by adding the validation rule. If the checkbox of a set is selected, the related 'person_item' textfield must be validated (else not).

I think I understand why the function for 'required' does not work (because of 'nr', but I dont know how to write the correct code).(PS: the validation rule does work with respect to the 'maxlength' and 'float' validation types)

for(var nr=0;nr<maxitems;nr++){
    form = getSingleform(nr,type);
    $("#wrapper").append(form);
    $("#person_item"+nr).rules("add", { 
      required: function(element) {return ($('#chckbox'+nr).is(':checked') ); },
      maxlength: 3,
      float:true, 
}); //rules add
}//for
Joppo
  • 715
  • 2
  • 12
  • 31
  • 1
    Can you show more of the code. It depends on how you've declared the `nr` variable in the containing function. – Barmar Sep 13 '13 at 20:06
  • '#chckbox'+nr is that a typo? you don't shorten the #person_item – Vlad Sep 13 '13 at 20:13
  • @Barmar: pls see update above – Joppo Sep 13 '13 at 20:14
  • @Vlad: '#chckbox'+nr refers to the id's of the checkboxes (chckbox0, chckbox1, etc...) – Joppo Sep 13 '13 at 20:16
  • @user2543182 I got that..I was just wondering if it's #chckbox should be #checkbox. It was weird that you only shortened the word checkbox but everywhere else you use the full words. – Vlad Sep 13 '13 at 20:18
  • Try this - call .validate() before adding rule. Here is the similar thread that might help - http://stackoverflow.com/questions/3033910/jquery-how-to-dynamically-add-a-validation-rule – Mutant Sep 13 '13 at 20:19
  • @Vlad: no, it's not a type error.... – Joppo Sep 13 '13 at 20:20
  • @mutant: that's correct and I have added the validate() before. As indicated in my text the validation for 'maxlength' and 'float' does work. – Joppo Sep 13 '13 at 20:22

1 Answers1

1

You need to use an immediately-executing function to close over nr.

for(var nr=0;nr<maxitems;nr++){
    form = getSingleform(nr,type);
    $("#wrapper").append(form);
    $("#person_item"+nr).rules("add", { 
        required: (function(nr) {
            return function(element) {return ($('#chckbox'+nr).is(':checked') ); };
        })(nr),
        maxlength: 3,
        float:true, 
    }); //rules add
}//for

See Why is this function wrapped in parentheses, followed by parentheses? for an explanation of immediately executing functions in Javascript.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • that works, thnx! I'm just still a beginner, can u pls elaborate a bit about this 'immediately-executing function' ? – Joppo Sep 13 '13 at 20:34