Scenario:
I have a masterpage, and there is a search text box on it. For most pages, when the page is loaded, I want to set focus on the search box; for other pages, to a control on that page.
Rather than set focus on every page, I create a pulic function in a class. For those pages the focus is set to a specific control, this function is called.
public void SetFocus(string vControl)
{
string strJS;
strJS = "<script>" +
"var o = document.getElementById('" + vControl + "'); " +
"if((o != undefined) && (o != null)){ " +
"if(window.attachEvent) " +
"window.attachEvent('onload',new function(){o.focus();}); " +
"else " +
"window.addEventListener('load',new function(){o.focus();},true); }" +
"</script>";
((Page)System.Web.HttpContext.Current.Handler).ClientScript.RegisterStartupScript(this.GetType(), "CSSetFocus", strJS);
}
Meanwhile, on the master page, I have the following javascript code right after the search box control. The position of this piece of code is important. If it is before the search box control, getElementById() gets nothing; if it is located somewhere after the javascript code generated by SetFocus(), then the focus always stays on the search box control.
<script>
var o = document.getElementById('<%=txtSearch.ClientID%>'+'_Input');
if((o != undefined) && (o != null)) o.focus();
</script>
Of course, .NET can set focus by this.TextBox1.Focus(); however, if multiple master pages are used, I prefer using my own javascript code to control when and where the focus is set.