简体   繁体   English

自动回发功能后将焦点设置回正确的文本框

[英]Set focus back to the proper textbox after autopostback function

Now, this MAY look a duplicate, but it's not.现在,这可能看起来是重复的,但它不是。
Every solution on the internet shows you how to get focus on the textbox that fired the event. Internet 上的每个解决方案都向您展示了如何将焦点放在触发事件的文本框上。

But what if the user presses tab?但是如果用户按下 tab 键呢? The textbox that should have focus is the next one.应该具有焦点的文本框是下一个。
So we do a workaround and focus on the textbox that have TabIndex higher than the one that fired the event.因此,我们采取了一种解决方法,并专注于 TabIndex 高于触发事件的文本框。

But then what if the user presses Shift+tab?但是如果用户按下 Shift+tab 会怎样呢?
Even worse: what if the user clicks on another random textbox?更糟糕的是:如果用户点击另一个随机文本框怎么办?

This is the issue.这就是问题所在。
I don't think a code is required here, because it's a general solution to set focus on textboxes that have autopostback function.我认为这里不需要代码,因为它是将焦点设置在具有自动回发功能的文本框上的通用解决方案。
If code is required, please ask in the comments.如果需要代码,请在评论中询问。

try, with SetFocus method on the server side尝试,在服务器端使用 SetFocus 方法

Page.SetFocus(IdOfControl);

I had a similar problem and I fixed it using a hidden field where I store the last component that the user select(click or tab) and after the postback, it will set the focus back to this component.我有一个类似的问题,我使用隐藏字段修复了它,我在其中存储了用户选择的最后一个组件(单击或选项卡),并且在回发之后,它将焦点设置回该组件。

Create hidden field in your page:在您的页面中创建隐藏字段:

<asp:HiddenField runat="server" ID="hiddenCurrentFocus" ClientIDMode="static"></asp:HiddenField>

Set the OnFocusIn in all the components where you wish to set the focus back.在您希望重新设置焦点的所有组件中设置 OnFocusIn。 Example:例子:

<asp:TextBox runat="server" ID="txtConfirmTransitId" OnFocusIn="setFocus(this.name)" ></asp:TextBox>

Create a JS function to store the name of the component in that hidden field(I'm using jQuery here, but you can do it with plain JS as well):创建一个 JS 函数来将组件的名称存储在该隐藏字段中(我在这里使用 jQuery,但您也可以使用普通 JS 来实现):

<script type="text/javascript">
    function setFocus(x) {
        $("#hiddenCurrentFocus").val(x);
    }
</script>

Now finally on the backend, you will set the focus after the postback现在终于在后端,您将在回发后设置焦点

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            //Set focus to the proper control
            var currentFocus = hiddenCurrentFocus.Value.ToString();
            if(!String.IsNullOrEmpty(currentFocus))
            {
                Page.SetFocus(Page.FindControl(currentFocus));
            }
            
        }
    }

This as a similar solution to the one that Jason suggested in the post below, but I prefer to store it in a hidden field:这与 Jason 在下面的帖子中建议的解决方案类似,但我更喜欢将其存储在隐藏字段中:

Set focus back to the proper textbox after autopostback function (Page.SetFocus doesn't solve the issue) 在自动回发功能后将焦点设置回正确的文本框(Page.SetFocus 没有解决问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM