开发者

Set always Focus on Textbox (ASP.NET, Updatepanel)

开发者 https://www.devze.com 2023-01-18 20:26 出处:网络
Hey, Before I start to write my problem, I will excuse for my bad English and I hope you can understand me.

Hey, Before I start to write my problem, I will excuse for my bad English and I hope you can understand me.

I have in a ASP.NET Webapplication an AJAX Updatepanel. In this Updatepanel is a Textbox for dynamic search results. When I start to write in the Textbox, the results comes like Google suggest.

Now, the focus must be always on the Textbox (inputn field), now metter whereto the User clicks.

Currently the ASP.NET u开发者_运维技巧pdatepanel refreshed after a few seconds when the User starts to type.

Thanks for help :-)


there is an event when updatepanel finish updated html dom

Sys.WebForms.PageRequestManager.getInstance().add_endRequest

try this

function EndRequestHandler() {  
//get focus on the textbox
myTextbox.focus(); }

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);


That is pretty fun but here is a possible solution. The idea is: if user gets out of the textbox (onblur), then take him back to the textbox (focusOnTxt function):

<head runat="server">
    <title></title>
    <script type="text/javascript">
        function focusOnTxt(sender) {
            sender.focus(); 
            sender.value = sender.value;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="upnl" runat="server">
        <ContentTemplate>
            <asp:TextBox ID="txt" runat="server"
          onblur="focusOnTxt(this)"></asp:TextBox>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

And on Page_Load:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txt.Focus();
    }
}


A simple SetFocus f.e. in Page.Load should work:

ScriptManager1.SetFocus (TextBox1.ClientID)

UPDATE: according to this post following works...

Add this script into a script block in your page's head:

function SetEnd(TB){
    if (TB.createTextRange){
        var FieldRange = TB.createTextRange();
        FieldRange.moveStart('character', TB.value.length);
        FieldRange.collapse();
        FieldRange.select();
    }
}

Then add the onfocus event to your Textbox:

onfocus="SetEnd(this)"

In your codebehind's Page.Load or TextChanged-Event handler add the standard SetFocus call:

ScriptManager sm = ScriptManager.GetCurrent(this);
sm.SetFocus(myTextBox)
0

精彩评论

暂无评论...
验证码 换一张
取 消