Dynamically
enable or disable RequiredFieldValidator using JQuery.
Javascript Code :-
<script type="text/javascript" src="../Scripts/jquery-1.10.2.js"></script>
$(document).ready(function () {
var var_RFV_txtDate = $get('<%=RFV_txtDate.ClientID %>');
var_RFV_txtDate.enabled = false;
$('#<%=span_txtDate.ClientID %>').hide();
ddlStatus_change();
});
function ddlStatus_change() {
$('#<%=ddlStatus.ClientID %>').change(function () {
var var_ddlStatus = $("#<%=ddlStatus.ClientID %> option:selected").text();
var var_RFV_txtDate = $get('<%=RFV_txtDate.ClientID %>');
var var_txtReturnedDt = $get('<%=txtReturnedDt.ClientID %>');
if
(var_ddlStatus.toLowerCase().indexOf("--select--") > -1) {
var_RFV_txtDate.enabled
= true;
$('#<%=span_txtDate.ClientID %>').show();
}
else {
var_RFV_txtDate.enabled
= false;
$('#<%=span_txtDate.ClientID %>').hide();
}
return false;
})
}
HTML Code :-
Closed
date : <span id="span_txtDate" class="required" runat="server">*</span>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFV_txtDate" runat="server" ControlToValidate="txtDate"
Display="None" ErrorMessage="Closed Date" ValidationGroup="ValGroup_Required" />
<asp:DropDownList ID="ddlStatus" runat="server">
<asp:ListItem Text="--Select--" Value="--Select--"></asp:ListItem>
<asp:ListItem Text="Draft" Value="Draft"></asp:ListItem>
<asp:ListItem Text="Open" Value="Open"></asp:ListItem>
<asp:ListItem Text="Close" Value="Close"></asp:ListItem>
</asp:DropDownList>
I’ve been messing with enabling and disabling validators with jQuery too, and it’s surprisingly tricky to get the timing right. Your approach with checking the dropdown selection and toggling the RequiredFieldValidator seems clean, though I’d probably wrap the show/hide logic in a separate function just to keep things neat. Also, if anyone wants a smoother way to test this kind of stuff, you can try YouTube Vanced for quick tutorial clips—it’s saved me a lot of time.
ReplyDelete