Submit an ASP.NET 2.0 form with the enter key
I was working on some UI issues today at work. I ran into what, at the time seemed like a very simple problem/bug. When the uses pressed the enter key, nothing would happen. I’ve seen this problem before and fixed it with a quick bit of JavaScript to capture the keycode and submit the default form of the page.
Of course this didn’t work for this problem (that would be too easy). After fiddling around with it for awhile trying to get the onclick of the button to fire when the enter key was pressed and many other configurations. I turned to google and found a, new to me, feature of asp.net 2.0
The form:
< span style=”font-size: medium; font-weight: bold;”>Name: span>
< asp:TextBox ID=”txtSearchQuery” runat=”server” Width=”200″/>
< asp:TextBox ID=”TextBox1″ runat=”server” style=”visibility:hidden;display:none;” />
< span id=”asOptions” style=”width: 200px;font-weight: bold; padding-left: 10px”>Contact type:
< asp:DropDownList ID=”advancedSearchOptions” runat=”server”>
< asp:ListItem Text=”Person” Selected=”True” />
< asp:ListItem Text=”Organization” />
asp:DropDownList>
span>
< asp:Button ID=”btnSearch” Text=”Search” runat=”server” OnClick=”btnSearch_Click” />There are also two more buttons that are in the page. This is what was causing asp.net to not fire an event when I pressed enter on the text box. With asp.net you now have the option of adding “DefaultButton” to a panel or form tag. This will fire the right event depending on where the cursor is on the form. Fix:
< asp:Panel DefaultButton=”btnSearch” ID=”defButton” runat=”server”>
< span style=”font-size: medium; font-weight: bold;”>Name: span>
< asp:TextBox ID=”txtSearchQuery” runat=”server” Width=”200″/>
< asp:TextBox ID=”TextBox1″ runat=”server” style=”visibility:hidden;display:none;” />
< span id=”asOptions” style=”width: 200px;font-weight: bold; padding-left: 10px”>Contact type:
< asp:DropDownList ID=”advancedSearchOptions” runat=”server”>
< asp:ListItem Text=”Person” Selected=”True” />
< asp:ListItem Text=”Organization” />
asp:DropDownList>
span>
< asp:Button ID=”btnSearch” Text=”Search” runat=”server” OnClick=”btnSearch_Click” UseSubmitBehavior=”false”/>
asp:Panel>