问题
A TextBox
is set to AutoPostback
as changing the value should cause a number of (display-only) fields to be recalculated and displayed.
That works fine.
However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.
I want the focus to be on the new field, not the textbox I've just changed. Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?
回答1:
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found this article in CodeProject which should do the trick.
回答2:
You could also consider refresh display-only fields using AJAX UpdatePanel. This way you won't lose focus from the new field.
Also I have proposed pure server-side solution based on WebControl.Controls.TabIndex analysis, you can use it, if you like.
回答3:
This is what is happening:
1) TAB on a field - client event
2) Focus on next field - client event
3) Postback - server event
4) Page redrawn - client event new page overrides preious client events
The solution of your problem is to:
a) get the element that has gained focus BEFORE postback
<script>
var idSelected;
$("input").focusin(function () {
idSelected = this.id;
});
</script>
b) store the ClientID (actually in var idSelected
) somewhere (i.e. an hidden Textbox, vith ViewState = true) BEFORE postback
** b) get ClientID ** (extract from hidden TextBox and put it in var idSelected
) AFTER postback
d) get the element with ClientID and set focus AFTER postback
<script>
$(document).ready(function () {
if (idSelected != null) {
$("#" + idSelected).focus();
idSelected = null;
});
});
</script>
Note: this sample scripts use JQuery.
Remember to put Jquery.js
in your solution and a reference in your page
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<asp:ScriptManager runat="server" >
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery.js" ScriptMode="Auto" />
....
Note2: this solution works without AJAX.
Look at this answer: to make Javascript work over Ajax you must use code like this:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
MyScript();
}
</script>
来源:https://stackoverflow.com/questions/173810/autopostback-with-textbox-loses-focus