6

I have a dropdown selector, with values from 1-4. Depending on the selection, subsequent inputs in form are hidden and validation required is removed from each. eg, if 2 is selected, then inputs 1-2 are shown and validation required is added whilst 3-4 are hidden and validation removed.

$("#dropdownSelector").change(function() {
inputtohide = $(this).val();
$('input[id*=conviction]').slice(0, inputtohide).show().rules("add", {required: "#convictions_0:checked" });
$('input[id*=conviction]').slice(inputtohide, 4).hide().rules("remove", {required: "#convictions_0:checked" });
$("#thisform").validate();
});

This works fine, however ( as the documentation for the validation plugin states ) validation is only added for the first element returned.

I understand from other posts , that the following code should add validation to each input:-

$("#thisform").validate();
$("input[id*=conviction]").each(function() {
    $(this).rules("add", {required: "#convictions_0:checked" });

    });

My question is how do I combine the two bits of code ? Any help greatly appreciated, thanks.

Sparky
  • 98,165
  • 25
  • 199
  • 285
naturelab
  • 79
  • 1
  • 2
  • 10

1 Answers1

5

You simply need to use the .each() function on your .slice() result in order to iterate over all the elements it returns:

$('input[id*=conviction]').slice(0, inputtohide).each(function(){
    $(this).show().rules("add", {required: "#convictions_0:checked" });
});

$('input[id*=conviction]').slice(inputtohide, 4).each(function(){
    $(this).hide().rules("remove", {required: "#convictions_0:checked" });
});

Hope this helps !

Valentin Flachsel
  • 10,795
  • 10
  • 44
  • 67
  • Thanks @FreekOne, that was a great help. It added the rules correctly, but the show / hide stopped working correctly. I changed it a bit and it works now - thankyou :- `code`$('input[id*=conviction]').slice(0, inputtohide).show().each(function(){ $(this).rules("add", {required: "#convictions_0:checked" }); }); $('input[id*=conviction]').slice(inputtohide, 4).hide().each(function(){ $(this).rules("remove", {required: "#convictions_0:checked" }); }); `code` – naturelab Jun 14 '12 at 16:43
  • @naturelab I'm not sure why the `show` / `hide` would stop working since the code is correct, but I'm glad I could help! – Valentin Flachsel Jun 14 '12 at 21:36