Thursday, March 30, 2006

Hiding controls in ASP.NET

If you use control.visible = false for controls in your web application these will not be rendered to the resulting HTML. If you want to interact with the control via Javascript there are going to be problems...

Fortunatly one of my Enterprise .NET students found a potential solution. Try the following in your web applications:

control.Style.Add("display","block"); // makes visible
control.Style.Add("display","none"); // makes invisible

Thanks for finding this solution.

The following script can be used to show and hide controls based on the state of a checkbox.

<script language="javascript">
var ieDOM = false, nsDOM = false;
var stdDOM = document.getElementById;

function initMethod()
{
//Determine the browser support for the DOM
if( !stdDOM )
{
ieDOM = document.all;

if( !ieDOM )
{
nsDOM = ((navigator.appName.indexOf('Netscape') != -1) && (parseInt(navigator.appVersion) ==4));
}
}

checkedChanged();
}

function getObject(objectId)
{
if (stdDOM) return document.getElementById(objectId);
if (ieDOM) return document.all[objectId];
if (nsDOM) return document.layers[objectId];
}

function getObjectStyle(objectId)
{
if (nsDOM) return getObject(objectId);

var obj = getObject(objectId);
return obj.style;
}

function show(objectId)
{
var objs = getObjectStyle(objectId);
objs.visibility = 'visible';
}

function hide(objectId)
{
var objs = getObjectStyle(objectId);
objs.visibility = 'hidden';
}

function checkedChanged()
{
var chkBox = getObject('chkBox');

chkBox.checked ? show('txtCreditLimit') : hide('txtCreditLimit');
}
</script>

initMethod() must be called when the page loads: <body onload="initMethod();">

You also need to add some code to the page load to register the checkChanged with the click event on the checkbox. chkBox.Attributes.Add("onclick", "checkedChanged();");

This then allows the control to be shown and hidden using client side Java script.

No comments: