ValidatorEnable Javascript function
I have a dropdownlist with different options like Name, Phone, Date etc. There is a textbox in which I enter values for these options. Each of these options have validator controls associated with it. On selecting the dropdown, only the validators specific to the selected value should fire
Here is the ASPX markup that contains the dropdownlist, textbox and validators
<form id="form1" runat="server"> <div> <asp:DropDownList ID="TypeList" runat="server" OnChange="TypeList_Change(this);"> <asp:ListItem Value="Name" Selected="True">Name</asp:ListItem> <asp:ListItem Value="Date">Date</asp:ListItem> <asp:ListItem Value="Phone">Phone</asp:ListItem> </asp:DropDownList> </div> <asp:TextBox ID="ValueText" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="NameReq" runat="server" ControlToValidate="ValueText">*</asp:RequiredFieldValidator> <asp:RequiredFieldValidator ID="DateReq" runat="server" ControlToValidate="ValueText">*</asp:RequiredFieldValidator> <asp:CompareValidator ID="DateVal" runat="server" ControlToValidate="ValueText" Type="Date" Operator="DataTypeCheck">*</asp:CompareValidator> <asp:CompareValidator ID="PhoneVal" runat="server" ControlToValidate="ValueText" Type="Integer" Operator="DataTypeCheck">*</asp:CompareValidator> <asp:Button ID="SubmitBtn" runat="server" Text="Submit"/> </form>
To enable or disable a validator, the javascript ValidatorEnable(val, enable) can be used. The way to find the list of validators for a particular selection is to hard-code the validator IDs in a 2D array. The javascript function for OnChange event handler of the dropdownlist is given below:
<script type="text/javascript" > var list = [['NameReq'], ['DateReq', 'DateVal'], ['PhoneVal']]; function TypeList_Change(c) { for (var i = 0; i < list.length; i++) { var valList = list[i]; var enabled = (i == c.selectedIndex); for (var j = 0; j < valList.length; j++) { var validator = document.getElementById(valList[j]); ValidatorEnable(validator, enabled); } } } </script>When the document is loaded initially or on any postback, the validators have to be enabled appropriately. So add this code to the body onload eventhandler
<body onload="TypeList_Change(document.getElementById('TypeList'));">
Posted by Vijay on 08-Oct-2009 12:05 PM
Category : Javascript
Category : Javascript


