Introduction
A problem occurs when a TextBox
having its width set in percentage is placed in a table. If there is some initial value in the TextBox
, then IE sets the width incorrectly.
Background
When a TextBox
is assigned width in percentage, the actual width it takes is a percentage of its container. Normally, this works fine, but if the TextBox
is placed inside a table, then IE renders it correctly only if the TextBox
is empty to begin with. However, if there is some initial value in the TextBox
when the page is loaded, then IE sets the minimum width of the TextBox
to the actual content. As a result, if the calculated width of the TextBox
is more than this value, the TextBox
expands, but if the calculated width is smaller than this value, it takes the initial width. This behavior occurs only when the TextBox
is inside a table.
Using the code
I scouted around for a fix for this typical problem. Many suggested using a multiline textbox, i.e., a TextBox
with Rows
=1, but it still allowed multiple line entry. Then, I noticed a curious behavior in the sense that only the TextBox
es that have an initial value were affected by this problem. Any data entered in the other TextBox
es were behaving normally. I modified my TextBox
es to have an empty initial value and stuffed the actual contents after page load. This functionality has been wrapped in a nice reusable function below. This function may be placed in a common module as a static function.
public void FixTextBoxes()
{
Page thePage = HttpContext.Current.Handler as Page;
if (thePage == null) return;
if (!thePage.Request.Browser.Browser.ToLower().Contains("ie"))
return;
string sScript;
if (!thePage.IsClientScriptBlockRegistered("processTB"))
{
sScript = "function processTB(restoreMode)" +
"{if(typeof restoreMode == 'undefined')restoreMode=false;";
sScript += "var i=0,theCtls=document.getElementsByTagName('input');";
sScript += "for(i=0;i<theCtls.length;i++){";
sScript += "if(theCtls[i].type.toLowerCase()=='text'){";
sScript += "if(restoreMode){if(theCtls[i].xVal!='undefined')" +
"theCtls[i].value=theCtls[i].xVal;";
sScript += "}else {var xWidth=theCtls[i].style.width;";
sScript += "theCtls[i].xVal=theCtls[i].value;theCtls[i].value='';";
sScript += "theCtls[i].style.width=theCtls[i].offsetWidth+'px';" +
"theCtls[i].style.width=xWidth;";
sScript += "}}}if(!restoreMode)window.setTimeout('processTB(true)',1);};";
thePage.RegisterClientScriptBlock("processTB", sScript, true);
}
if (!thePage.IsStartupScriptRegistered("fixTB"))
{
sScript = "window.setTimeout('processTB()',100);";
thePage.RegisterStartupScript("fixTB", sScript, true);
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.