tags:

views:

31

answers:

3

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 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.

+1  A: 
<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

Mike
+2  A: 

You can do a couple things.

  1. 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"> ....
    
  2. 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) ... ")
womp
how can I change this from __doPostBack to actually click the button. I've got ASP.NET's AJAX doing an asyncPostBack on button click and want the preserve that?
jamone
You can call click() on the button by doing `document.getElementById('<%= btnSearch.UniqueID %>').click()`;
womp
A: 

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">
alejandrobog
Just tried it, doesn't work.
jamone