Recently, I started exploring ASP.NET.
In my project, there are three ASP controls: a textbox, a dropdown, and a submit button.
The requirement is that if the dropdown option is selected, then the textbox should be a mandatory field. However, if no dropdown option is selected, then the textbox should not be mandatory. Currently, I am facing an issue where the required field validator still triggers even when no dropdown option is selected.
To address this challenge, I have implemented a JavaScript solution to check if the textbox is empty and disable the required field validation accordingly.
<td><label for="schoolName">SCHOOLNAMES</label></td>
<td><asp:TextBox ID="txtschoolname" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorSchoolName" runat="server"
ControlToValidate="txtschoolname" ForeColor="Red"
ErrorMessage="Required"></asp:RequiredFieldValidator>
</td>
<td>Bank Name</td>
<td>
<select">
<option>Please select the bank</option>
<option value="DBN">DBN</option>
<option value="CCC">CCC</option>
</select>
</td>
<td colspan="2">
<asp:Button ID="Button1" runat="server" Text="submit"
OnClientClick=" validate();" onclick="Button1_Click" />
JavaScript:
function validate() {
var txt = document.getElementById("txtschoolname");
alert(txt);
var ddlObj = document.getElementById("<%=txtschoolname.ClientID%>");
var validatorObject = document.getElementById("<%=RequiredFieldValidatorSchoolName.ClientID%>");
alert(ddlObj);
if (txt == null) {
validatorObject.enabled = false;
// validatorObject.isvalid = true;
}
}