How to check the required text if the "Other" option is selected in the drop-down list?

I have the following on my site.

Source [DropDownList]

Site

Search system

Other

Another source [TextBox]

I want to use ASP.Net validators (I think the comparison validator), so when "Other" is selected in the drop-down list and the text is not entered, the check is activated and the page cannot be sent.

Is it possible?

Ive tried setting the value of the Other parameter to the string.empty drop-down list and comparing it to an empty text field, but that didn't work.

Everything that I inherited is inside the wizard's control, otherwise I would connect some client script to initiate the check. I don’t think I can do this with a wizard?

Thanks in advance.

+6
validation drop-down-menu
source share
2 answers

None of the ASP.NET validators provided allows for conditional validation based on another control. However, you can achieve this using CustomValidator, which performs client-side, server-side, or both (at least server-side verification is recommended). Validators work well with masters.

ASP.NET markup example:

<asp:DropDownList ID="OptionsDropDownList" runat="server"> <asp:ListItem Text="Website" /> <asp:ListItem Text="Search Engine" /> <asp:ListItem Text="Other" /> </asp:DropDownList> <asp:TextBox ID="OtherTextBox" runat="server" /> <asp:CustomValidator ID="custvOptionsDropDownList" runat="server" ControlToValidate="OptionsDropDownList" ValidateEmptyText="true" Display="Dynamic" ClientValidationFunction="validateOtherTextBox" ErrorMessage="This field is required!" OnServerValidate="ValidateOtherTextBox" /> 

Javascript for ClientValidationFunction:

 <script type="text/javascript" language="javascript"> function validateOtherTextBox(event, args) { var textbox = document.getElementById('<%= OtherTextBox.ClientID %>').value; if (args.Value == 'Other') args.IsValid = (textbox != ''); else args.IsValid = true; } </script> 

Code for OnServerValidate:

  protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args) { if (OptionsDropDownList.SelectedValue == "Other") { args.IsValid = (OtherTextBox.Text.Trim() != ""); } } 

Please note that it is your choice to implement everything you need. You can completely skip Javascript validation and remove this code and the ClientValidationFunction attribute. Also note that Javascript references the target control using the ClientID property. This is necessary because ASP.NET assigns a different identifier when the page is displayed, and you want it to be provided to the Javascript method this way (look at the source code on the page and you will see that the control name has an additional prefix, etc. .).

+9
source share

you check which option in the list is selected from the drop-down list, for example

 if (ddl.selecteditemindex == 1){ if (txtvalue.text == "") { alert('you write something if selected other otherwise choose from a list'); } } 
0
source share

All Articles