Using jQuery to disable RequiredFieldValidators

I use jQuery to hide / show div depending on the selected value of the combo box. This part is working fine. However, when hiding the div, the jquery function should also disable the 3 RequiredFieldValidators that are in this div. I look online and it seems that this can be easily done using:

ValidatorEnable(ValidatorName, false); 

But when I try to use this method, nothing works, RequiredFieldValidators still display an error, even if the div is hidden.

My jQuery function:

 <script type="text/javascript"> $(document).ready(function () { var det = $("#SponsorDetails"); $(det).hide(); var all = $("#AllDetails"); $(all).hide(); $("#<%=SelectAccount.ClientID %>").click(function () { //hide social worker and sponsor stuff var value = $("#<%=SelectAccount.ClientID %> option:selected").val(); if (value == "Social_Worker") { //show social worker stuff $("#AllDetails").show("slow"); $("#SponsorDetails").hide("slow"); ValidatorEnable(document.getElementById("#<%=AddressValidator.ClientID %>"), false); ValidatorEnable(document.getElementById("#<%=CityValidator.ClientID %>"), false); ValidatorEnable(document.getElementById("#<%=CountryValidator.ClientID %>"), false); } else if (value == "Sponsor") { //show sponsor stuff $("#AllDetails").show("slow"); $("#SponsorDetails").show("slow"); ValidatorEnable(document.getElementById("#<%=AddressValidator.ClientID %>"), true); ValidatorEnable(document.getElementById("#<%=CityValidator.ClientID %>"), true); ValidatorEnable(document.getElementById("#<%=CountryValidator.ClientID %>"), true); } }); }); </script> 

Someone suggested I use validation groups or a custom validator, but using jquery seems a lot easier, but I don't know why this will not work.

+4
source share
2 answers

You confuse jQuery with simple javascript. In simple javascript, we do not use the # character before the element identifier. So remove it from all getElementById and it will work.

for instance

 document.getElementById("<%=CountryValidator.ClientID %>") 

The error is caused by the fact that you call getElementById without checking their return, so you get a throw error from using the return of this function, which cannot be used.

+3
source

You can use the following code snippet to activate manual verification manually to run ... use in jQuery

  ValidatorEnable($("[id$='RegularExpressionValidator4']")[0], true); 
0
source

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


All Articles