Multiple buttons on form, after clicking one how to select the other as the defualt ASP.NET
I have a ASP.NET form that has a search box, with a Go button. When you first visit the page and type in the search you can hit enter to click the go button. Then when presented with the list of results you click another button to mark the selected result for use. Then I allow the user to repeat to their hart's content to select multiple results. However the 2nd+ time that you enter a search query and hit enter 开发者_StackOverflow社区it clicks the button instead of the button. You can see in the browser (IE7+) that the button is selected dispite you typing into the search field. How can I revert it so that after ever button press it selects the button as default?
I've tried using btnGo.Focus() in the button's onClick but that has no effect.
You can do a couple things.
Set the
DefaultButton
property of the form to the ID of your search button. This can work in a few situations, but lots of people have trouble with it, especially with complex or dynamic forms. Give it a try, simplest is best.<form runat="server" DefaultButton="btnSearch"> ....
Add a javascript handler to the textbox in question, such that no matter the structure of the page, it will always click the search button when they press enter. The easiest way to do it would be with jQuery:
$("#myTextBox").keydown(function(e) { if (e.keyCode == 13) { __doPostBack('" + <%= btnSearch.UniqueID + "','')"); } });
but you could do something similar in the codebehind by adding an attribute to the textbox:
myTextBox.Attributes.Add("onKeyPress", "if (event.keyCode == 13) ... ")
<asp:Panel ID="pnl1" runat="server" DefaultButton="ImageButton1">
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:ImageButton ID="ImageButton1" runat="server" />
</asp:Panel>
or
http://weblogs.asp.net/jeff/archive/2005/07/26/420618.aspx
This should work:
<script language="javascript" type="text/javascript">
function FocusButton() {
var btn = document.getElementById('<%= btnGo.ClientID %>');
btn.Focus();
}
</script>
Then on your search textbox
<asp:TextBox ID="SearchTxt" runat="server" onClick="FocusButton">
精彩评论