Saturday, January 23, 2010

Enabled/Disabled Validator using JavaScript

In web projects there are many situations when you have to disabled the validator of asp.net control depending on the state of the checkbox, if check box is checked then you can disabled the validor and when check box is unchecked then you can enabled the validator. Here is the main form of the test example which consist of a drop down list control , checkbox and two button one for save and other one for cancel. You can see that check box is checked and the drop down list control is displayed, which is the default behaviour.



Now when check box in unchecked then text box is displayed and the validator control for the dopdown list control is disabled and the validator for the text box is endabled. And also dropdown list control is not hide and the text box control is displayed you can see this behaviour in the image below.


Here is the simple java script which is used to hide and show the control and also to enabled disabled the validators. Here I have used the enabled property of the validator , I set the value to true when the corresponding control is shown and set false when the corresponding control is not hidden.

function EnabledDisabledValidator() {
var currentControl = document.getElementById("<%=chkOther.ClientID %>");
var rfvTextBox = document.getElementById('<%=rfvTextBox.ClientID%>');
var txtJobTitle = document.getElementById("<%=txtJobTitle.ClientID %>");
var rfvDropDownList = document.getElementById('<%=rfvDropDownList.ClientID%>');
var ddlJobTitle = document.getElementById("<%=ddlJobTitle.ClientID %>");

if (currentControl != null) {
if (currentControl.checked) {
rfvDropDownList.enabled= true;
ddlJobTitle.style.display = '';
rfvTextBox.enabled= false;
txtJobTitle.style.display = 'none';
}
else {
rfvDropDownList.enabled= false;
ddlJobTitle.style.display = 'none';
rfvTextBox.enabled= true;
txtJobTitle.style.display = '';
}
}
}
By using java script to enabled disabled the validator we can save the post back of the page, mean we can set it on the client side as well, What you have to do is to set the status of the control on the page load by calling the the javascript and also to attach the click event with the check box control, so that when user click on the check box the hide and show of the control take place and also enabled disabeld the validators.You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

No comments: