Wednesday, June 30, 2010

Auto focus textbox

To auto focus the first textbox on each pageload:

1.) Copy the function below into the base page:
private void FocusFirstTextBox(){
  StringBuilder buildScript = new StringBuilder();
  buildScript.Append("var boxes = document.getElementsByTagName('input');");
  buildScript.Append("for(var i = 0; i < boxes.length; i++) {");
  buildScript.Append("if(boxes[i].type == 'text' && boxes[i].disabled == false && boxes[i].style.display != 'none'){");
  buildScript.Append("boxes[i].focus();");
  buildScript.Append("break;");
  buildScript.Append("}}");

  this.RegisterStartupScript(Guid.NewGuid().ToString(),
  "");
}


2.) Copy this function call into the base pages OnPreRender:
protected override void OnPreRender(EventArgs e) {
  base.OnPreRender (e);
  this.FocusFirstTextBox();
}