Set focus to a TextBox (in a ModalPopupExtender)

I have a web page where couple of ModalPopupExtender and Panel exist, and I want to set focus to TextBox inside the corresponding pop up window when user click the target button accordingly. I think it's a common requirement to set the focus to a specific TextBox immediately when user open up the window. However, I always get the error message "Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus".

Understand that the modal pop up window and the TextBox inside are hidden by default, while setting focus on that TextBox upon the click of TargetControl seems impossible. Fortunately, google showed me an article by Jaspreet and he showed how he solve this problem by using the setTimeOut and two JavaScript functions (set the focus by 1 second delay).

7 Comments

  • I want to know answer this

  • where can i find out the source code and javascript for doing this...

  • Sys.Application.add_load(function() {
    var popup = $find('');
    popup.add_shown(function() { $get('').focus(); });
    });

    P.S/ add_shown event *

  • Hi,
    This code is working fine with IE7 and IE8.
    But not working in firefox.

  • Hi,

    Thanks.It is working in firefox also.

  • If (Not Me.ClientScript.IsStartupScriptRegistered("FocusText")) Then
    Dim sb As StringBuilder = New StringBuilder()
    sb.Append("")
    sb.Append("Sys.Application.add_load(modalSetup);")
    sb.Append("function modalSetup() {")
    sb.Append(String.Format("var modalPopup = $find('{0}');", ModalPopupExtender2.BehaviorID))
    sb.Append("modalPopup.add_shown(SetFocusOnControl); }")
    sb.Append("function SetFocusOnControl() {")
    sb.Append(String.Format("var textBox1 = $get('{0}');", Me.txtdisponible.ClientID))
    sb.Append("textBox1.focus();}")
    sb.Append("")
    Page.ClientScript.RegisterStartupScript(Page.GetType(), "FocusText", sb.ToString())
    End If

  • wher we have to place that code?

Comments have been disabled for this content.