JQuery validation: adding / removing rules Dynamically based on a selection of drop-down list

I have a dropdown selector with values ​​from 1 to 4. Depending on the choice, the subsequent inputs in the form are hidden, and the required validation is removed from each. for example, if 2 is selected, then inputs 1-2 are displayed, and a check is added, while 3-4 are hidden and the check is deleted.

$("#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 great, however (as documentation for validation plugin states) validation is only added for the first item returned.

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

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

My question is how to combine two bits of code? Any help is much appreciated, thanks.

+6
source share
1 answer

You just need to use the .each() function for the .each() result to .slice() over all the returned elements:

 $('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!

+5
source

Source: https://habr.com/ru/post/918033/


All Articles